算法設(shè)計(jì)思想如下:
(1)設(shè)置初始區(qū)間,low=1;high=length,
折半查找算法的實(shí)現(xiàn)
。(2)當(dāng)low>high時(shí),返回查找失敗信息。
(3)取中點(diǎn),low<=high,mid=(low+high)/2。
a.若kx
b.若kx>a[mid],查找改在右半?yún)^(qū)進(jìn)行,low=mid+1;轉(zhuǎn)向步驟(2)。
c.若ax=a[mid],查找成功,返回?cái)?shù)據(jù)位置。
代碼實(shí)現(xiàn):
#include <stdio.h>int b_search(int x, int a[], int n) //折半查找函數(shù){ int low = 0; int high = n ; if (low > high) { return -1; } else { while (low <= high) { int mid = (low + high) / 2; if (a[mid] < x) { low = mid + 1; } else if (a[mid] > x) { high = mid - 1; } else { return mid; } } } return -1;}int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int key = 0; int sz = sizeof(arr) / sizeof(arr[0]); scanf("%d", &key); int ret = b_search(key, arr, sz); if (ret == -1) { printf("不存在這個(gè)數(shù)!\n"); } else { printf("%d\n", ret); } return 0;}