C语言基础:二分查找法演示代码
#include <stdio.h> int binary_search(int array[], int value, int size) { int found = 0; int high = size, low = 0, mid; mid = (high + low) / 2; printf("\n\nLooking for %d\n", value); while ((! found) && (high >= low)) { printf("Low %d Mid %d High %d\n", low, mid, high); if (value == array[mid]) found = 1; else if (value < array[mid]) high = mid - 1; else low = mid + 1; mid = (high + low) / 2; } return((found) ? mid: -1); } int main(void) { int array[100], i; for (i = 0; i < 100; i++) array[i] = i; printf("Result of search %d\n", binary_search(array, 33, 100)); printf("Result of search %d\n", binary_search(array, 75, 100)); printf("Result of search %d\n", binary_search(array, 1, 100)); printf("Result of search %d\n", binary_search(array, 1001, 100)); return 1; }
输出结果
Looking for 33 Low 0 Mid 50 High 100 Low 0 Mid 24 High 49 Low 25 Mid 37 High 49 Low 25 Mid 30 High 36 Low 31 Mid 33 High 36 Result of search 33 Looking for 75 Low 0 Mid 50 High 100 Low 51 Mid 75 High 100 Result of search 75 Looking for 1 Low 0 Mid 50 High 100 Low 0 Mid 24 High 49 Low 0 Mid 11 High 23 Low 0 Mid 5 High 10 Low 0 Mid 2 High 4 Low 0 Mid 0 High 1 Low 1 Mid 1 High 1 Result of search 1 Looking for 1001 Low 0 Mid 50 High 100 Low 51 Mid 75 High 100 Low 76 Mid 88 High 100 Low 89 Mid 94 High 100 Low 95 Mid 97 High 100 Low 98 Mid 99 High 100 Low 100 Mid 100 High 100 Result of search -1