二分法查找

<!-- lang: cpp -->
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int binary_search(int len, int num[], int request) {
int left = 0, right = len - 1, mid;
while (left < right) {
    mid = (left+right)/2; 
    if (request <= num[mid]) { 
        right = mid;
    } else { 
        left = mid+1; 
    }
}

if (request > num[len-1] ) left++;
return left;
}
int main() {
int num[10] = {1, 3, 4, 5, 7, 8, 8, 9, 10, 13};
printf("%d\n", binary_search(10, num, 6));
return 0;
}

你可能感兴趣的:(二分法查找)