其他分享
首页 > 其他分享> > 二分搜索(折半查找)

二分搜索(折半查找)

作者:互联网

二分搜索(折半查找)

伪代码

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;
}

标签:折半,二分,right,int,mid,BinarySearch,查找,numbers,left
来源: https://blog.csdn.net/weixin_45252450/article/details/111356632