交换排序(冒泡排序和快速排序)
基于交换的排序算法有两种:冒泡排序和快速排序。
冒泡排序
冒泡排序算法描述:比较相邻两个元素大小,如果反序,则交换。若按升序排列,每趟将数据序列中的最大元素交换到最后位置,就像气泡从水里冒出一样。
冒泡排序算法分析:
- 最好情况,数据序列排序,只需一趟扫描,比较n次,没有数据移动,时间复杂度为O(n)。最坏情况,数据序列随机排列和反序排列,需要n-1趟扫描,比较次数和移动次数都是O(n^ 2),时间复杂度为(n^ 2)。总之,数据序列越接近有序,冒泡排序算法时间效率越高,在O(n)到O(n^2)之间。
- 冒泡排序需要一个辅助空间用于交换两个元素,空间复杂度为O(1)。
冒泡排序算法是稳定的。
一个冒泡排序的过程图:
冒泡排序算法如下:
package book;
/**
* 交叉排序(升序)
*/
public class crossSort {
public static void main(String[] args) {
int[] keys = {32,26,87,72,26,17};
int[] keys2 = {2,3,1,5,7,4,6};
bubbleSort1(keys2);
print(keys2);
System.out.println();
System.out.println("-----------------------");
int[] keys3 = {2,3,1,5,7,4,6};
bubbleSort2(keys3);
print(keys3);
System.out.println();
System.out.println("-----------------------");
int[] keys4 = {2,3,1,5,7,4,6};
bubbleSort3(keys4);
print(keys4);
}
//冒泡排序1
public static void bubbleSort1(int[] keys) {
//外层循环控制轮数
for (int i = keys.length-1; i > 0; i--) {
//内层循环,比较大小,做交换
for (int j = 0; j < i; j++) {
if (keys[j] > keys[j + 1]) {
swap(keys, j, j+1);
}
System.out.format("第 %d 遍第%d 趟结果:", keys.length-i, j+1);
for(int count:keys) {
System.out.print(count);
System.out.print(",");
}
System.out.println("");
}
}
}
//冒泡排序2-第一次优化(减少外循环)
//我们设置一个标志位,用来表示当前第 i 趟是否有交换,如果有则要进行 i+1 趟,
//如果没有,则说明当前数组已经完成排序,省去无用循环
public static void bubbleSort2(int[] keys) {
//外层循环控制轮数
for (int i = keys.length-1; i > 0; i--) {
//标志位 1代表没有交换,0代表发生了交换
int flag = 1;
//内层循环,比较大小,做交换
for (int j = 0; j < i; j++) {
if (keys[j] > keys[j + 1]) {
swap(keys, j, j+1);
flag = 0;
}
System.out.format("第 %d 遍第%d 趟结果:", keys.length-i, j+1);
for(int count:keys) {
System.out.print(count);
System.out.print(",");
}
System.out.println("");
}
//说明上一轮的比较没有交换元素,可以直接结束循环
if (flag == 1) {
break;
}
}
}
//冒泡排序2-第二次优化(减少外循环,减少内循环)
//在增加标志位,确认下一次是否还需要循环的基础上
//问题:就是第 i 趟排的第 i 小或者大的元素已经在第 i 位上了,
// 甚至可能第 i-1 位也已经归位了,
// 那么在内层循环的时候,有这种情况出现就会导致多余的比较出现,
// 因为这些比较没有发生交换操作
//解决:针对上述的问题,我们可以利用一个标志位,记录一下当前第 i 趟所交换的最后一个位置的下标,
//在进行第 i+1 趟的时候,只需要内循环到这个下标的位置就可以了,
//因为后面位置上的元素在上一趟中没有换位,这一次也不可能会换位置了
public static void bubbleSort3(int[] keys) {
int len = keys.length-1;
//记录最后一次交换的位置
int tempPostion = 0;
//外层循环控制轮数(要遍历的次数)
for (int i = 0; i < len; i++) {
//标志位 1代表没有交换,0代表发生了交换
int flag = 1;
//内层循环,比较大小,做交换
for (int j = 0; j < len-i; j++) {
if (keys[j] > keys[j + 1]) {
swap(keys, j, j+1);
flag = 0;
tempPostion = j;//记录交换的位置
}
System.out.format("第 %d 遍第%d 趟结果:", i+1, j+1);
for(int count:keys) {
System.out.print(count);
System.out.print(",");
}
System.out.println("");
}
//把最后一次交换的位置给len,来缩减内循环的次数
len = tempPostion;
//说明上一轮的比较没有交换元素,则已经有序,可以直接结束循环
if (flag == 1) {
break;
}
}
}
//交换
static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//打印
static void print(int[] arr){
for (int i : arr) {
System.out.print(i+",");
}
}
}
//看一下输出结果:
第 1 遍第1 趟结果:2,3,1,5,7,4,6,
第 1 遍第2 趟结果:2,1,3,5,7,4,6,
第 1 遍第3 趟结果:2,1,3,5,7,4,6,
第 1 遍第4 趟结果:2,1,3,5,7,4,6,
第 1 遍第5 趟结果:2,1,3,5,4,7,6,
第 1 遍第6 趟结果:2,1,3,5,4,6,7,
第 2 遍第1 趟结果:1,2,3,5,4,6,7,
第 2 遍第2 趟结果:1,2,3,5,4,6,7,
第 2 遍第3 趟结果:1,2,3,5,4,6,7,
第 2 遍第4 趟结果:1,2,3,4,5,6,7,
第 2 遍第5 趟结果:1,2,3,4,5,6,7,
第 3 遍第1 趟结果:1,2,3,4,5,6,7,
第 3 遍第2 趟结果:1,2,3,4,5,6,7,
第 3 遍第3 趟结果:1,2,3,4,5,6,7,
第 3 遍第4 趟结果:1,2,3,4,5,6,7,
第 4 遍第1 趟结果:1,2,3,4,5,6,7,
第 4 遍第2 趟结果:1,2,3,4,5,6,7,
第 4 遍第3 趟结果:1,2,3,4,5,6,7,
第 5 遍第1 趟结果:1,2,3,4,5,6,7,
第 5 遍第2 趟结果:1,2,3,4,5,6,7,
第 6 遍第1 趟结果:1,2,3,4,5,6,7,
1,2,3,4,5,6,7,
-----------------------
第 1 遍第1 趟结果:2,3,1,5,7,4,6,
第 1 遍第2 趟结果:2,1,3,5,7,4,6,
第 1 遍第3 趟结果:2,1,3,5,7,4,6,
第 1 遍第4 趟结果:2,1,3,5,7,4,6,
第 1 遍第5 趟结果:2,1,3,5,4,7,6,
第 1 遍第6 趟结果:2,1,3,5,4,6,7,
第 2 遍第1 趟结果:1,2,3,5,4,6,7,
第 2 遍第2 趟结果:1,2,3,5,4,6,7,
第 2 遍第3 趟结果:1,2,3,5,4,6,7,
第 2 遍第4 趟结果:1,2,3,4,5,6,7,
第 2 遍第5 趟结果:1,2,3,4,5,6,7,
第 3 遍第1 趟结果:1,2,3,4,5,6,7,
第 3 遍第2 趟结果:1,2,3,4,5,6,7,
第 3 遍第3 趟结果:1,2,3,4,5,6,7,
第 3 遍第4 趟结果:1,2,3,4,5,6,7,
1,2,3,4,5,6,7,
-----------------------
第 1 遍第1 趟结果:2,3,1,5,7,4,6,
第 1 遍第2 趟结果:2,1,3,5,7,4,6,
第 1 遍第3 趟结果:2,1,3,5,7,4,6,
第 1 遍第4 趟结果:2,1,3,5,7,4,6,
第 1 遍第5 趟结果:2,1,3,5,4,7,6,
第 1 遍第6 趟结果:2,1,3,5,4,6,7,
第 2 遍第1 趟结果:1,2,3,5,4,6,7,
第 2 遍第2 趟结果:1,2,3,5,4,6,7,
第 2 遍第3 趟结果:1,2,3,5,4,6,7,
第 2 遍第4 趟结果:1,2,3,4,5,6,7,
第 3 遍第1 趟结果:1,2,3,4,5,6,7,
1,2,3,4,5,6,7,
快速排序
快速排序是一种分区交换排序算法。
首先分析一下冒泡排序,在冒泡排序中存在这样一种情况:如上面冒泡排序中在序列{32,26,87,72,26,17}中,元素87在相邻位置间经过若干次连续的交换到达最终位置,元素87移动了多次才到达最终位置,存在重复的数据移动。快速排序算法希望尽可能地减少这样重复的数据移动。
快速排序(Quick Sort)算法描述:在数据序列中选择一个元素作为基准值,每趟从数据序列的两端开始交替进行,将小于基准值的元素交换到序列前端,将大于基准值的元素交换到序列后端,介于两者之间的位置则成为基准值的最终位置。同时,序列被划分成两个子序列,再分别对两个子序列进行快速排序,直到子序列长度为1,则完成排序。
一个快速排序案例分析:
关键字序列{38,38,97,75,61,19,26,49}快速排序(升序)一趟划分过程如下图所示,{}表示待排序子序列。
对存于keys数组begin~end之间的子序列进行一趟快速排序,设i、j下标分别从子序列的前后两端开始,i=begin, j=end,划分算法描述如下:
-
1、选取子序列第一个元素keys[i] 38作为基准值vot,空出keys[i]元素位置。
-
2、在子序列后端寻找小于基准值的元素,交换到序列前端。即比较keys[j]元素26与基准值,若小则将keys[j]元素26移动到序列前端keys[i]位置,i++,此时keys[j]位置空出。
-
3、在子序列前端寻找大于基准值的元素,交换到序列后端。再比较keys[i]元素与基准值,若大则将keys[i]元素97移动到序列后端的keys[j]位置,j–,keys[i]位置空出。不移动与基准值相等元素。(其实对于以上步骤2 3 也可以同时进行,将 一个比一个比基准数小的 与 一个比基准数大的 做交换。)
-
4、重复执行2 3,直到i==j【这就是临界条件】,表示子序列中的每个元素都与基准值比较过了,并已将小于基准值的元素移动到前端,将大于基准值的元素移动到后端,当前 i(j) 位置则是基准值的最终位置。观察上图的数据移动情况,一趟划分过程中,只用6次赋值,就使5个元素移动位置。
-
5、一趟快速排序将数据序列划分成两个子序列,范围分别为begin~j-1、i+1~end。每个子序列均较短,再对两个子序列分别进行快速排序【需要递归】,直到子序列长度为1【算法结束的条件】。
-
这里要注意的是:因为第一步选择的序列的第一个元素为轴(基准数),所以第二步中是从后往前找比基准数小的来填充基准数的位置(不能先从前往后找比基准数大的,因为找到的数没有地方存放,如果硬要放,就会改变序列中的值);如果一开始选择的是序列中最后一个数来作为基准数,那么应该先从前往后找比基准数大的,再从后往前找比基准数小。
上述数据序列的快速排序(升序)过程如下图所示,{}表示待排序子序列。
快速排序算法采用分治策略对两个子序列再分别进行快速排序,因此,快速排序是递归算法。
快速排序算法:
package book;
/**
* 交叉排序(升序) 只有快速排序
*
*/
public class crossSort2 {
public static void main(String[] args) {
int[] keys = {38,38,97,75,61,19,26,49};
int[] keys2 = {7,3,2,6,8,1,9,5,4,6,10,6};
quickSort(keys,0,keys.length-1);
//quickSortBook(keys);
print(keys);
}
//quickSortBook 是按照上面的分析步骤实现的。
public static void quickSortBook(int[] keys){
System.out.println("快速排序(升序)");
quickSortBook(keys, 0, keys.length-1);
}
//对存于keys数组begin~end之间的子序列进行一趟快速排序,递归算法
private static void quickSortBook(int[] keys, int begin, int end) {
//序列有效
if (begin>=0 && begin<keys.length && end>=0 && end<keys.length && begin<end){
int i=begin, j=end; //i、j下标分别从子序列的前后两端开始
int vot=keys[i]; //子序列第一个值作为基准值
while (i!=j) {
//(升序)从后向前寻找比基准数小值,不移动与基准值相等元素
while (i<j && keys[j]>=vot) j--;
if (i<j){
keys[i++]=keys[j]; //子序列后端较小元素向前移动
}
//(升序)从前向后寻找比基准数大值,不移动与基准值相等元素
while (i<j && keys[i]<=vot) i++;
if (i<j){
keys[j--]=keys[i]; //子序列前端较大元素向后移动
}
}
keys[i]=vot; //基准值到达最终位置
System.out.print("下标"+begin+"~"+end+", vot="+vot+", ");
print(keys);
System.out.println();
quickSortBook(keys, begin, j-1); //前端子序列再排序,递归调用
quickSortBook(keys, i+1, end); //后端子序列再排序,递归调用
}
}
//quickSort 的逻辑是 将上面步骤2 3同时进行,将 一个比基准数小的 与 一个比基准数大的 做交换。
public static void quickSort(int[] keys, int begin, int end){
if (begin >= end) return; //数组只有一个元素
int mid = pritition1(keys, begin, end); //轴(基准数)的位置
//int mid = pritition2(keys, begin, end); //轴(基准数)的位置
quickSort(keys, begin, mid-1);//对左区间进行快速排序
quickSort(keys, mid+1, end);//对右区间进行快速排序
}
public static int pritition1(int[] keys, int begin, int end){
int vot = keys[begin];//以数组第一个元素为基准
int left = begin + 1;//这里减+1 是因为排除基准数
int right = end;
//这里left <= right中的 = 是为了防止只有两个数时不走循环
while (left <= right) {
while (left <= right && keys[left] <= vot) //加上left <= right 防止下标越界
left++; //从前向后找一个比基准数大的
while (left <= right && keys[right] > vot)
right--; //从后向前找一个比基准数小的
if (left < right) {
//将找到的 一个比基准数小的 与 一个比基准数大的 做交换
swap(keys, left, right);
}
}
//一趟走完,将基准数放在两个序列之间(它该去的地方),而right就是它的位置
swap(keys, right, begin);
return right;//返回基准数的位置
}
public static int pritition2(int[] keys, int begin, int end){
int vot = keys[end];//以数组最后一个元素为基准
int left = begin;
int right = end - 1;//这里减-1 是因为排除基准数
//这里left <= right中的 = 是为了防止只有两个数时不走循环
while (left <= right) {
//加上left <= right 防止下标越界
while (left <= right && keys[left] <= vot)
left++; //从前向后找一个比基准数大的
while (left <= right && keys[right] > vot)
right--; //从后向前找一个比基准数小的
if (left < right) {
//将找到的 一个比基准数小的 与 一个比基准数大的 做交换
swap(keys, left, right);
}
}
//一趟走完,将基准数放在两个序列之间(它该去的地方),而left就是它的位置
swap(keys, left, end);
return left;//返回基准数的位置
}
//交换
static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//打印
static void print(int[] arr){
for (int i : arr) {
System.out.print(i+",");
}
}
}
快速排序算法分析
快速排序的执行时间与数据序列的初始排列及基准值的选取有关,分析如下。
-
最好情况,每趟排序将序列分成长度相近的两个子序列,时间复杂度为O(n×log2n)。
-
最坏情况,每趟将序列分成长度差异很大的两个子序列,时间复杂度为O(n^2)。
- 例如,设一个排序数据序列有n个元素,若选取序列的第一个值作为基准值,则第一趟得到的两个子序列长度分别为 0 和 n-1,这样必须经过n-1趟才能完成排序,因此,比较次数C越等于(n^2)/2
快速排序选择基准值还有其他多种方法,如可以选取序列的中间值等。但由于序列的初始排列是随机的,不管如何选择基准值,总会存在最坏情况。
此外,快速排序还要在执行递归函数过程中花费一定的时间和空间,使用栈保存参数,栈所占用的空间与递归调用的次数有关,空间复杂度为O(log2n)~O(n)。
总之,当n较大且数据序列随机排列时,快速排序是“快速”的;当n很小或基准值选取不合适时,快速排序则较慢。快速排序算法是不稳定的。
快速排序改进-双轴快排
上述快速排序的思想是:找到一个轴(基准数),比轴小的放左边,比轴大的放右边,然后把轴放中间,之后在左序列和右序列中再执行以上步骤,直到子序列长度为1,则完成排序。
双轴快排的设计思想:找两个轴(两个基准数m,n),整个序列被分为三部分,<m 的在左边,>=m and <= n的在中间,>n的在右边,前提是:m < n。
我们来看一下java源码:Arrays.sort()。
Arrays.sort();
public class Arrays {
public static void sort(int[] a) {
DualPivotQuicksort.sort(a, 0, a.length - 1, null, 0, 0);
}
}
final class DualPivotQuicksort {
/**
* The maximum number of runs in merge sort.
*/
private static final int MAX_RUN_COUNT = 67;
/**
* If the length of an array to be sorted is less than this
* constant, Quicksort is used in preference to merge sort.
*/
private static final int QUICKSORT_THRESHOLD = 286;
/**
* If the length of an array to be sorted is less than this
* constant, insertion sort is used in preference to Quicksort.
*/
private static final int INSERTION_SORT_THRESHOLD = 47;
/**
* Sorts the specified range of the array using the given
* workspace array slice if possible for merging
*
* @param a the array to be sorted
* @param left the index of the first element, inclusive, to be sorted
* @param right the index of the last element, inclusive, to be sorted
* @param work a workspace array (slice)
* @param workBase origin of usable space in work array
* @param workLen usable size of work array
*/
static void sort(int[] a, int left, int right,
int[] work, int workBase, int workLen) {
// Use Quicksort on small arrays
//如果数组长度小于286,使用之前的快速排序算法
if (right - left < QUICKSORT_THRESHOLD) {
sort(a, left, right, true);
return;
}
/*
* Index run[i] is the start of i-th run
* (ascending or descending sequence).
*/
//检查这个数组是否适合用teamsort(一种改进的归并排序)
int[] run = new int[MAX_RUN_COUNT + 1];
int count = 0; run[0] = left;
// Check if the array is nearly sorted
for (int k = left; k < right; run[count] = k) {
if (a[k] < a[k + 1]) { // ascending
while (++k <= right && a[k - 1] <= a[k]);
} else if (a[k] > a[k + 1]) { // descending
while (++k <= right && a[k - 1] >= a[k]);
for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
int t = a[lo]; a[lo] = a[hi]; a[hi] = t;
}
} else { // equal
for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
if (--m == 0) {
sort(a, left, right, true);
return;
}
}
}
/*
* The array is not highly structured,
* use Quicksort instead of merge sort.
*/
//不适合用teamsort,用快速排序
if (++count == MAX_RUN_COUNT) {
sort(a, left, right, true);
return;
}
}
// Check special cases
// Implementation note: variable "right" is increased by 1.
if (run[count] == right++) { // The last run contains one element
run[++count] = right;
} else if (count == 1) { // The array is already sorted
return;
}
// Determine alternation base for merge
byte odd = 0;
for (int n = 1; (n <<= 1) < count; odd ^= 1);
// Use or create temporary array b for merging
int[] b; // temp array; alternates with a
int ao, bo; // array offsets from 'left'
int blen = right - left; // space needed for b
if (work == null || workLen < blen || workBase + blen > work.length) {
work = new int[blen];
workBase = 0;
}
if (odd == 0) {
System.arraycopy(a, left, work, workBase, blen);
b = a;
bo = 0;
a = work;
ao = workBase - left;
} else {
b = work;
ao = 0;
bo = workBase - left;
}
// Merging
for (int last; count > 1; count = last) {
for (int k = (last = 0) + 2; k <= count; k += 2) {
int hi = run[k], mi = run[k - 1];
for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) {
b[i + bo] = a[p++ + ao];
} else {
b[i + bo] = a[q++ + ao];
}
}
run[++last] = hi;
}
if ((count & 1) != 0) {
for (int i = right, lo = run[count - 1]; --i >= lo;
b[i + bo] = a[i + ao]
);
run[++last] = right;
}
int[] t = a; a = b; b = t;
int o = ao; ao = bo; bo = o;
}
}
/**
* Sorts the specified range of the array by Dual-Pivot Quicksort.
*
* @param a the array to be sorted
* @param left the index of the first element, inclusive, to be sorted
* @param right the index of the last element, inclusive, to be sorted
* @param leftmost indicates if this part is the leftmost in the range
*/
//快速排序
private static void sort(int[] a, int left, int right, boolean leftmost) {
int length = right - left + 1;
// Use insertion sort on tiny arrays
//数组长度是否小于47,小于就用插入排序
if (length < INSERTION_SORT_THRESHOLD) {
if (leftmost) {
/*
* Traditional (without sentinel) insertion sort,
* optimized for server VM, is used in case of
* the leftmost part.
*/
for (int i = left, j = i; i < right; j = ++i) {
int ai = a[i + 1];
while (ai < a[j]) {
a[j + 1] = a[j];
if (j-- == left) {
break;
}
}
a[j + 1] = ai;
}
} else {
/*
* Skip the longest ascending sequence.
*/
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
/*
* Every element from adjoining part plays the role
* of sentinel, therefore this allows us to avoid the
* left range check on each iteration. Moreover, we use
* the more optimized algorithm, so called pair insertion
* sort, which is faster (in the context of Quicksort)
* than traditional implementation of insertion sort.
*/
//双插入排序
for (int k = left; ++left <= right; k = ++left) {
int a1 = a[k], a2 = a[left];
if (a1 < a2) {
a2 = a1; a1 = a[left];
}
while (a1 < a[--k]) {
a[k + 2] = a[k];
}
a[++k + 1] = a1;
while (a2 < a[--k]) {
a[k + 1] = a[k];
}
a[k + 1] = a2;
}
int last = a[right];
while (last < a[--right]) {
a[right + 1] = a[right];
}
a[right + 1] = last;
}
return;
}
// Inexpensive approximation of length / 7
//下面是取轴的过程,将数组长度除7 为步长(1/7为多大)
int seventh = (length >> 3) + (length >> 6) + 1;
/*
* Sort five evenly spaced elements around (and including) the
* center element in the range. These elements will be used for
* pivot selection as described below. The choice for spacing
* these elements was empirically determined to work well on
* a wide variety of inputs.
*/
//取数组最后一个元素下表,减去步长得到一个数,再减步长得到一个数...
int e3 = (left + right) >>> 1; // The midpoint
int e2 = e3 - seventh;
int e1 = e2 - seventh;
int e4 = e3 + seventh;
int e5 = e4 + seventh;
// Sort these elements using insertion sort
//将找到的五个数排好序
if (a[e2] < a[e1]) { int t = a[e2]; a[e2] = a[e1]; a[e1] = t; }
if (a[e3] < a[e2]) { int t = a[e3]; a[e3] = a[e2]; a[e2] = t;
if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
}
if (a[e4] < a[e3]) { int t = a[e4]; a[e4] = a[e3]; a[e3] = t;
if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
}
}
if (a[e5] < a[e4]) { int t = a[e5]; a[e5] = a[e4]; a[e4] = t;
if (t < a[e3]) { a[e4] = a[e3]; a[e3] = t;
if (t < a[e2]) { a[e3] = a[e2]; a[e2] = t;
if (t < a[e1]) { a[e2] = a[e1]; a[e1] = t; }
}
}
}
//下面从五个数中根据具体情况得到两个轴
// Pointers
//两个轴
int less = left; // The index of the first element of center part
int great = right; // The index before the first element of right part
if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {
/* 如果五个数都不想等,取第二个和第四个数为轴
* Use the second and fourth of the five sorted elements as pivots.
* These values are inexpensive approximations of the first and
* second terciles of the array. Note that pivot1 <= pivot2.
*/
int pivot1 = a[e2];
int pivot2 = a[e4];
/*
* The first and the last elements to be sorted are moved to the
* locations formerly occupied by the pivots. When partitioning
* is complete, the pivots are swapped back into their final
* positions, and excluded from subsequent sorting.
*/
a[e2] = a[left];
a[e4] = a[right];
/*
* Skip elements, which are less or greater than pivot values.
*/
while (a[++less] < pivot1);
while (a[--great] > pivot2);
/*
* Partitioning:
*
* left part center part right part
* +--------------------------------------------------------------+
* | < pivot1 | pivot1 <= && <= pivot2 | ? | > pivot2 |
* +--------------------------------------------------------------+
* ^ ^ ^
* | | |
* less k great
*
* Invariants:
*
* all in (left, less) < pivot1
* pivot1 <= all in [less, k) <= pivot2
* all in (great, right) > pivot2
*
* Pointer k is the first index of ?-part.
*/
//找到两个轴之后,往三个分区中移动元素
outer:
for (int k = less - 1; ++k <= great; ) {
int ak = a[k];
if (ak < pivot1) { // Move a[k] to left part
a[k] = a[less];
/*
* Here and below we use "a[i] = b; i++;" instead
* of "a[i++] = b;" due to performance issue.
*/
a[less] = ak;
++less;
} else if (ak > pivot2) { // Move a[k] to right part
while (a[great] > pivot2) {
if (great-- == k) {
break outer;
}
}
if (a[great] < pivot1) { // a[great] <= pivot2
a[k] = a[less];
a[less] = a[great];
++less;
} else { // pivot1 <= a[great] <= pivot2
a[k] = a[great];
}
/*
* Here and below we use "a[i] = b; i--;" instead
* of "a[i--] = b;" due to performance issue.
*/
a[great] = ak;
--great;
}
}
// Swap pivots into their final positions
a[left] = a[less - 1]; a[less - 1] = pivot1;
a[right] = a[great + 1]; a[great + 1] = pivot2;
// Sort left and right parts recursively, excluding known pivots
sort(a, left, less - 2, leftmost);
sort(a, great + 2, right, false);
/*
* If center part is too large (comprises > 4/7 of the array),
* swap internal pivot values to ends.
*/
if (less < e1 && e5 < great) {
/*
* Skip elements, which are equal to pivot values.
*/
while (a[less] == pivot1) {
++less;
}
while (a[great] == pivot2) {
--great;
}
/*
* Partitioning:
*
* left part center part right part
* +----------------------------------------------------------+
* | == pivot1 | pivot1 < && < pivot2 | ? | == pivot2 |
* +----------------------------------------------------------+
* ^ ^ ^
* | | |
* less k great
*
* Invariants:
*
* all in (*, less) == pivot1
* pivot1 < all in [less, k) < pivot2
* all in (great, *) == pivot2
*
* Pointer k is the first index of ?-part.
*/
outer:
for (int k = less - 1; ++k <= great; ) {
int ak = a[k];
if (ak == pivot1) { // Move a[k] to left part
a[k] = a[less];
a[less] = ak;
++less;
} else if (ak == pivot2) { // Move a[k] to right part
while (a[great] == pivot2) {
if (great-- == k) {
break outer;
}
}
if (a[great] == pivot1) { // a[great] < pivot2
a[k] = a[less];
/*
* Even though a[great] equals to pivot1, the
* assignment a[less] = pivot1 may be incorrect,
* if a[great] and pivot1 are floating-point zeros
* of different signs. Therefore in float and
* double sorting methods we have to use more
* accurate assignment a[less] = a[great].
*/
a[less] = pivot1;
++less;
} else { // pivot1 < a[great] < pivot2
a[k] = a[great];
}
a[great] = ak;
--great;
}
}
}
// Sort center part recursively
//递归继续排
sort(a, less, great, false);
} else { // Partitioning with one pivot
//刚刚那五个数中有相等的,去第三个为轴,做快速排序
/*
* Use the third of the five sorted elements as pivot.
* This value is inexpensive approximation of the median.
*/
int pivot = a[e3];
/*
* Partitioning degenerates to the traditional 3-way
* (or "Dutch National Flag") schema:
*
* left part center part right part
* +-------------------------------------------------+
* | < pivot | == pivot | ? | > pivot |
* +-------------------------------------------------+
* ^ ^ ^
* | | |
* less k great
*
* Invariants:
*
* all in (left, less) < pivot
* all in [less, k) == pivot
* all in (great, right) > pivot
*
* Pointer k is the first index of ?-part.
*/
for (int k = less; k <= great; ++k) {
if (a[k] == pivot) {
continue;
}
int ak = a[k];
if (ak < pivot) { // Move a[k] to left part
a[k] = a[less];
a[less] = ak;
++less;
} else { // a[k] > pivot - Move a[k] to right part
while (a[great] > pivot) {
--great;
}
if (a[great] < pivot) { // a[great] <= pivot
a[k] = a[less];
a[less] = a[great];
++less;
} else { // a[great] == pivot
/*
* Even though a[great] equals to pivot, the
* assignment a[k] = pivot may be incorrect,
* if a[great] and pivot are floating-point
* zeros of different signs. Therefore in float
* and double sorting methods we have to use
* more accurate assignment a[k] = a[great].
*/
a[k] = pivot;
}
a[great] = ak;
--great;
}
}
/*
* Sort left and right parts recursively.
* All elements from center part are equal
* and, therefore, already sorted.
*/
sort(a, left, less - 1, leftmost);
sort(a, great + 1, right, false);
}
}
}