二分搜索(折半查找)

二分搜索(折半查找)

伪代码

function BinarySearch(List,key) {
  left = 0,right = Lis.length - 1
  while left <= right 
    mid = (left + right) / 2
    if List[mid] is key 
      return mid 
    if List[mid] < key 
      left = mid + 1;
    else 
      right = mid -1;
}

二分搜索(折半查找)
二分搜索(折半查找)

代码

#include <stdio.h>
int BinarySearch(int numbers[],int len,int key)
{
    int left=1,right=len;
    int mid;
    while(left <= right){
        mid=(left+right)/2;
        if(numbers[mid]==key)
            return mid;
        else if(numbers[mid]<key)
            left = mid+1;
        else 
            right = mid-1;
    }
    return 0;
}
int main() {
    int N;
    int K;
    int m;
    int numbers[1000001];
    // 反复读入数字和查找数字的数量
    while (scanf("%d%d", &N, &K) != EOF) {
        for (int i = 1; i <= N; i++) 
            scanf("%d", &numbers[i]);
        for (int j = 0; j < K; j++) {
            scanf("%d", &m);
            printf("%d",BinarySearch(numbers,N,m));
            if(j!=K-1)
                printf(" ");
        }
    }
    return 0;
}
上一篇:Java数组相关基本操作的实现


下一篇:Java binarysearch方法