折半查找
程序代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 10 // 插入排序(升序) void insertion_sort(int * data, int begin, int end) { int i, j, k, temp; for(i = begin + 1; i <= end; i++) { for(j = 0; j < i; j++) if(data[j] > data[i]) break; temp = data[i]; for(k = i; k > j; k--) data[k] = data[k - 1]; data[j] = temp; } } // 折半查找 ,找到该值则返回该值在数组中的索引,否则返回-1 int binary_search(const int * data, int value, int size) { int start = 0, stop = size - 1, middle = (start + stop) / 2; while(data[middle] != value && start < stop) { if(data[middle] > value) stop = middle - 1; else start = middle + 1; middle = (start + stop) / 2; } return data[middle] == value ? middle : -1; } int main(void) { int data[SIZE], i, index, value; // 数组中每个元素被置为随机数 srand((unsigned)time(NULL)); for(i = 0; i < SIZE; i++) data[i] = rand(); insertion_sort(data, 0, SIZE - 1); // 输出已排序好的值 for(i = 0; i < SIZE; i++) printf("%d ", data[i]); printf("\n"); // 输入一个值,并查找它在数组中的索引 scanf("%d", &value); index = binary_search(data, value, SIZE); printf("index : %d\n", index); return 0; }
跟据思路自己写的,但不知道对不对,请朋友们指教一下,Thanks!
[ 本帖最后由 lz1091914999 于 2011-6-13 12:33 编辑 ]