QuickSort代码实现(原创)
1 #include <iostream> 2 using namespace std; 3 4 int Partition( int *R, int low, int high){ 5 R[0] = R[low]; // 将枢轴记录移至数组的闲置分量 6 int pivotkey = R[low]; // 枢轴记录关键字 7 cout << endl << "pivotkey : " << pivotkey << endl; 8 while(low < high){ // 从表的两端交替地向中间扫描 9 while( low<high && R[high]>=pivotkey ){ 10 --high; 11 } 12 if(low < high){//需要进行这样的判断,如果是由于low>=high而退出的循环,不需要移动数据 13 R[low++] = R[high]; // 将比枢轴记录小的记录移到低端 14 } 15 while (low<high && R[low]<=pivotkey ) 16 ++low; 17 if(low < high){ 18 R[high--] = R[low]; // 将比枢轴记录大的记录移到高端 19 } 20 } // while 21 R[low] = R[0]; // 枢轴记录移到正确位置 22 for(int i = 1; i<=10; i++){ 23 cout << R[i-1] << " "; 24 } 25 return low; // 返回枢轴位置 26 } // Partition 27 void QSort(int *R, int s, int t ){ 28 // 对记录序列 R[s..t] 进行快速排序 29 if (s < t){ // 长度大于1 30 int pivotloc = Partition(R, s, t);// 对 R[s..t] 进行一趟快排,并返回枢轴位置 31 QSort(R, s, pivotloc-1);//对低子序列递归进行排序 32 QSort(R, pivotloc+1, t);//对高子序列递归进行排序 33 }//if 34 }//Qsort 35 int main(){ 36 int li[10] = {0,38,65,97,76,13,27,48,55,4}; 37 cout<<"This program has set R[0] as the free variable."<<endl; 38 for(int i = 1; i<=10; i++){ 39 cout << li[i-1] << " "; 40 } 41 cout << endl; 42 QSort(li,1,9); 43 cout << endl; 44 for(int i = 1; i<=10; i++){ 45 cout << li[i-1] << " "; 46 } 47 cout << endl; 48 return 0; 49 }