编程之美3.18后面的二分查找题解:
#include<stdlib.h> #include<stdio.h> //最大索引,等于k int 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; } //最小索引,等于k int 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; } //最小的索引,大于k int 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; } //最大的索引,小于k int 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; }