#include <stdio.h> #define VALUE 1 //搜索值 const unsigned int array[] = {1,2,3,4,5,6,7,8,9};
/* binsort函数功能:折半搜索value在数组array中的位置 array[] :升幂排序的数组 num :数组array的大小(元素个数) value :被搜索的值 return :若找到,则返回value在数组array的位置;反之返回-1 */ unsigned int binsort(const unsigned int array[], unsigned int num, const unsigned int value ) { /*
left :搜索区间的左边界 right :搜索区间的右边界 middle :搜索区间的搜索点 */ int left, right, middle; left = 0; right = num - 1; while (left <= right) { middle = (left + right)/2; if (value == array[middle]) return (middle + 1); if (value < array[middle]) right = middle - 1; else left = middle + 1; } return -1; }
int main() { unsigned int size = sizeof(array)/sizeof(unsigned int); printf("%d position in the array is %d\n", VALUE, binsort(array, size, VALUE)); return 0; }
|