二分搜尋(折半查詢)

聖穎君發表於2020-12-18

二分搜尋(折半查詢)

虛擬碼

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

相關文章