3.18二分搜索算法各种变种

来源:互联网 发布:王传君我不喜欢知乎 编辑:程序博客网 时间:2024/06/05 11:27

编程之美3.18后面的二分查找题解:

#include<stdlib.h>#include<stdio.h>//最大索引,等于kint bisearch(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] <= v) minIndex = midIndex;else maxIndex = midIndex - 1;}if (arr[maxIndex] == v) return maxIndex;else if (arr[minIndex] == v) return minIndex;else return -1; }//任意一个等于V的索引int bisearch2(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex <= maxIndex){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] == v) return midIndex;else if (arr[midIndex] < v) minIndex = midIndex + 1;else maxIndex = midIndex - 1;}return -1;}//最小索引,等于kint bisearch3(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] >= v) maxIndex = midIndex;else minIndex = midIndex + 1;}if (arr[minIndex] == v) return minIndex;else if (arr[maxIndex] == v) return maxIndex;return -1;}//最小的索引,大于kint bisearch4(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex <= maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] > v) maxIndex = midIndex;else minIndex = midIndex + 1;}if (arr[maxIndex] > v) return maxIndex;return -1;}//最大的索引,小于kint bisearch5(int* arr, int b, int e, int v){int minIndex = b, maxIndex = e, midIndex = 0;while (minIndex < maxIndex - 1){midIndex = minIndex + ((maxIndex - minIndex) >> 1);if (arr[midIndex] >= v) maxIndex = midIndex - 1;else minIndex = midIndex;}if (arr[maxIndex] < v) return maxIndex;if (arr[minIndex] < v) return minIndex;return -1;}int main(){int arr[] = {1,2,3,4,5,5,5,6,6,7,8,9,9};int k;while(1){scanf("%d",&k);printf("%d,%d\n",sizeof(arr)/sizeof(arr[0]),bisearch5(arr, 0, sizeof(arr)/sizeof(arr[0]) - 1,k));}return 0;}


原创粉丝点击