第一步:从伪代码到具体的C语言代码
一般版本:
int binarysearch(int arr[], int n, int key) { int low = 0, high = n; while(low < high) { int mid = low + (high - low) / 2; if(arr[mid] == key) { cout<<"fad"; return mid; } else if(arr[mid] > key) high = mid; else low = mid + 1; } return -1; }
递归版本:
int binarysearch(int arr[], int low, int high, int key) { if(low >= high) return -1; int mid = low + (high - low) / 2; cout<<"low :"<<low<<" high :"<<high<<" mid :"<<mid<<endl; count++; if(arr[mid] == key) return mid; else if(arr[mid] > key) binarysearch(arr, low, mid, key); else binarysearch(arr, mid + 1, high, key); }
scanf("%d %d", &n, &key); for(int i = 0; i < n; ++i) scanf("%d", &arr[i]); cout<<binarysearch(arr, n, key)<<endl;
通过上述五个步骤的开发,这时的程序就可以在需要的地方使用了。当然,如果在使用的过程中需求有了变化,则再进行同样的步骤进行修改就可以了。
以此为基础,分别写出lower_bound和upper_bound。(左闭右开)
#include<iostream> #include<cstring> #include<cstdio> #include<cstdlib> using namespace std; int lowbound(int arr[], int n, int key) { int low = 0, high = n; while(low < high) { int mid = (low + high) / 2; if(arr[mid] >= key) high = mid; else low = mid + 1; } return low; } int upperbound(int arr[], int n, int key) { int low = 0, high = n; while(low < high) { int mid = (low + high) / 2; if(arr[mid] <= key) low = mid + 1; else high = mid; } return high; } int main() { int arr[10]; for(int i = 0; i < 10; ++i) cin>>arr[i]; int p = lowbound(arr, 10, 4); int q = upperbound(arr, 10, 4); cout<<p<<" "<<q<<endl; return 0; }