快排(qucikSort)
#include <iostream> 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]; //we always put the value of first into the last, so the first is NULL at last
a[first] = key; //insert the centre elements QSort(a, low, first-1); QSort(a, first+1, high); } } int main() { int a[] = {57, 68, 59, 52, 72, 28, 96, 33, 24}; int n = sizeof(a)/sizeof(a[0]); QSort(a, 0, n-1); //third parameter minus one, otherwise array will overstep the boundary for(int i=0; i<n; i++) cout << a[i] << " "; return 0; }