Complexity: O(log(n))
Ref: Binary search algorithm or 二分搜索算法
Ref: C 版本 while 循环
C Language scripts by McDelfino:
#include <stdio.h> #include <stdlib.h> int getIndex(int* arr, int length, int num); int main() { int arr[100]; for (int i = 0; i < 100; i++) { arr[i] = i + 1; } for (int i = 1; i <= 100; i++) { printf("num = %d, find index = %d. ", i, getIndex(arr, 100, i)); } return 0; } int getIndex(int* arr, int length, int num) { int min = 0; int max = length - 1; int count = 0; while (1) { int avg = (min + max)/2; count++; if (arr[avg] < num) min = avg + 1; else if (arr[avg] > num) max = avg - 1; else { printf("-----count = %d----- ", count); return avg; } } }