快速排序的C++实现
#include <stdio.h> void swap(int a[], int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } int Partition_0(int a[], int low, int high) { int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分 // int i = low - 1;//i是最后一个小于主元的数的下标 for (int j = low; j < high; j++)//遍历下标由low到high-1的数 { if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数 { i++; swap(a,i,j); } } //经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换 a[high] = a[i + 1]; // a[i + 1] = x; return i + 1; } int Partition(int a[], int low, int high) { int tmp=a[low]; while (low<high) { while ((low<high)&&(a[high]>=tmp)) { high-=1; } if((low<high)&&(a[high]<tmp)) { a[low++]=a[high]; } while ((low<high)&&(a[low]<=tmp)) { low+=1; } if((low<high)&&(a[low]>tmp)) { a[high--]=a[low]; } } //low==high a[low]=tmp; return low; } void QuickSort(int a[], int low, int high) { if (low < high) { int q = Partition(a, low, high); QuickSort(a, low, q - 1); QuickSort(a, q + 1, high); } } void main() { int data[] = {7,1,6,4,3,2,1,23}; int length= sizeof(data)/sizeof(int); QuickSort(data, 0, length -1 ); for (int i=0;i<length;i++) { printf("%d,",data[i]); } printf("\n"); }
https://www.cnblogs.com/AlgrithmsRookie/p/5899160.html
partition函数的运行过程使用一个例子来帮助理解。对数组[6, 10, 10, 3, 7 ,1,8]运行一次Partition函数的过程如下图(有黄色填充的部分代表主元)所示:
其中i和j分别是程序当中的两个下标,j的作用是循环遍历,i的作用是指向小于主元的最后的一个数。当循环结束之后就将主元和i+1位置上面的数进行交换,这样就可以实现依据主元的大小对数组进行划分。




浙公网安备 33010602011771号