- 论坛徽章:
- 0
|
本帖最后由 jack1007 于 2012-10-23 15:30 编辑
二分查找算法很容易忽略了边界问题,导致在某些情况下查找失败,下面写了一个,斟酌了下边界问题,应该没有问题了,如果还有什么方法实现的,还请大家分享。- #include <stdio.h>
- int search(int *arr, int keys, int value);
- int
- main()
- {
- int arr[] = {1, 2, 3, 5, 7, 11, 18, 24, 53};
- int key;
- int value = arr[7];
- int keys = sizeof(arr) / sizeof(arr[0]);
- printf("There are %d keys\n", keys);
- key = search(arr, keys, value);
- printf("The key of value %d is %d\n", value, key);
- return 0;
- }
- int
- search(int *arr, int keys, int value)
- {
- int left = 0;
- int right = keys - 1;
- int midle;
- while (left <= right) {
- midle = (left + right) / 2;
- if (arr[midle] > value)
- right = midle -1;
- else if (arr[midle] < value)
- left = midle + 1;
- else
- return midle;
- }
- return -1;
- }
复制代码 |
|