快速排序与二分查找
#include <iostream> #include <string> using namespace std; void quicksort(int arry[], int low, int high) { if(low >= high) return; int l = low; int h = high; int key = arry[l]; while(l < h) { while(l < h && key < arry[h]){ --h; } if(l < h) { arry[l++] = arry[h]; } while(l < h && key > arry[l]){ ++l; } if(l < h) { arry[h--] = arry[l]; } } arry[l] = key; quicksort(arry, low, l - 1); quicksort(arry, l + 1, high); } bool binarysearch(int arry[], int n, int low, int high, int &key, int &index) { if(low > n - 1 || high < 0 || low > high) { cout<<"can't find "<<key<<endl; return false; } int middle = (low + high) % 2 == 0 ? (low + high) / 2 : (low + high) / 2 + 1; if(arry[middle] == key) { index = middle; return true; } else { if(arry[middle] > key) high = middle - 1; if(arry[middle] < key) low = middle + 1; } return binarysearch(arry, n, low, high, key, index); } int main() { int arry[] = {1,2,6,7,854,23,4,22,44,55}; int size = sizeof(arry)/sizeof(arry[0]); quicksort(arry, 0, size -1); cout<<"arry size is "<<size<<", after sort is:"<<endl; for(int i = 0; i < size; ++i) { cout<<arry[i]<<","; } cout<<endl; cout<<"binarysearch test."<<endl; int index; int value = 854; if(binarysearch(arry, size, 0, size - 1, value, index)) { cout<<"find "<<value<<" ok, index is "<<index<<endl; } value = 54; if(binarysearch(arry, size, 0, size - 1, value, index)) { cout<<"find "<<value<<" ok, index is "<<index<<endl; } return 0; }
2 2 4 9 3 6 7 1 5 首先用2当作基准,使用i j两个指针分别从两边进行扫描,把比2小的元素和比2大的元素分开。首先比较2和5,5比2大,j左移
2 2 4 9 3 6 7 1 5 比较2和1,1小于2,所以把1放在2的位置
2 1 4 9 3 6 7 1 5 比较2和4,4大于2,因此将4移动到后面
2 1 4 9 3 6 7 4 5 比较2和7,2和6,2和3,2和9,全部大于2,满足条件,因此不变
经过第一轮的快速排序,元素变为下面的样子
[1] 2 [4 9 3 6 7 5]