/*快速排序基本思想: 将待排序记录分割成两部分,其中一部分记录的关键字都不大于另外一部分记录的关键字, 然后再递归的对这两部分进行快速排序. */ #include<iostream> using namespace std; void swap(int &a,int &b) { int c = a; a = b; b = c; } int Partition(int L[],int low,int high) { //快速排序是一种交换排序. //一次快速排序,就是把比他小的交换到左边,比他大的交换到右边.由此该枢轴记录最后所落的位置就是分割线 int pivotKey = L[low]; while(low < high) { //因为枢轴选在第一个位置,所以从高端开始交换 while(low < high && L[high] >= pivotKey) high--; swap(L[low],L[high]); while(low < high && L[low] <= pivotKey) low++; swap(L[low],L[high]); } //结束的时候low==high,多么简单的逻辑.自己写的时候边界条件考虑了很久... return low; } //改进算法 //由于一次交换需要进行三次记录移动(赋值),而对枢轴记录的移动是多余的, //因为只有在排序结束的时候,确定了分割线才是对枢轴的最终移动. int Partition_improve(int L[],int low,int high) { int pivotKey = L[low]; int copyRecord = L[low]; while(low < high) { while(low < high && L[high] >= pivotKey) high--; L[low] = L[high]; while(low < high && L[low] <= pivotKey) low++; L[high] = L[low]; } L[low] = copyRecord; return low; } void QSort(int L[],int low,int high) { if(low < high) { //int pivotLoc = Partition(L,low,high); int pivotLoc = Partition_improve(L,low,high); QSort(L,low,pivotLoc - 1); QSort(L,pivotLoc + 1,high); } } void QuickSort(int L[],int len) { QSort(L,0,len-1); } int arr[11] = {10,2,35,6,7,8,2,3,41,29,3}; int main() { int len = sizeof(arr) / sizeof(int); QuickSort(arr,len); for(int i = 0;i < len;i++) cout<<arr[i]<<" "; system("Pause"); return 0; }