#include <iostream> #include <vector> #include <algorithm> using namespace std; void QSort(int a[], int low, int high) { if(low>=high) //关于这个终止条件, 在下边处理后,low可能会大于或等于high { return; } int first = low; int last = high; int key = a[first]; //use the first elements to be the key while(first<last) { while(first<last&&a[last]>=key) { last--; } a[first] = a[last]; while(first<last&&a[first]<=key) { first++; } a[last] = a[first]; a[first] = key; QSort(a, low, first-1); QSort(a, first+1, high); } } int NBinarySearch(vector<int> arr, int n, int target) { int low = 0, high = n - 1; //"low" is the low limit of search, "high" is the high limit of search while(low<=high) { int middle = (low + high) / 2; if(arr[middle]==target) { return middle; } else if(arr[middle]>target) { high = middle - 1; } else { low = middle + 1; } } return -1; //the target is not in the array } int BinarySearch(vector<int> arr, int target, int low, int high) { if(low>high) return -1; //recursive termination conditions are always a problem that needs to be explored,when low and high are equal, if the target value can not be found, this means the target value doesn't exist int middle = (low + high) / 2; //determines whethers the target values is equals to the value of "middle" position if(target==arr[middle]) { return middle; } else if(target>arr[middle]) { return BinarySearch(arr, target, middle+1, high); } else { return BinarySearch(arr, target, low, middle-1); } } bool com(int &a, int &b) //this is the parameter of sort { return a < b; } int main() { int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24}; vector<int> arr(a, a+9); vector<int>::iterator iter = arr.begin(); sort(arr.begin(), arr.end(), com); for(; iter!=arr.end(); iter++) cout << *iter << " "; cout << endl; int result = NBinarySearch(arr, 9, 52); cout << "the result of none_recurrence method: " << result << endl; result = BinarySearch(arr, 52, 0, 8); cout << "the result of recurrence method: " << result << endl; return 0; }
来源:https://www.cnblogs.com/1915884031A-qqcom/p/7588353.html