回顾一下算法导论,书上写的思想非常好。现再次实现看看。
快速排序的思想是:
每次排序都使一个能达到它排序后应该在的位置,其他的位置暂时不用管,所以可以让这个元素 X 把原本的序列分为 【小于X】 ,X, 【大于X】的3个部分。然后再二分递归求出每个元素应该的位置,至此就会把原来的序列排好序了。
----------------------------------------------------------------------------
❶
-1 0
i j temp(要排序的元素)
3 | 4 | 1 | 5 | 2 |
----------------------------------------------------------------------------
❷
0 2
i j temp(要排序的元素)
1 | 4 | 3 | 5 | 2 |
----------------------------------------------------------------------------
❸
0 4
i i+1 jtemp(要排序的元素)
1 | 2 | 3 | 5 | 4 |
(交换i+1 和 j 里 的值 即 交换 2 ,4)
----------------------------------------------------------------------------
首先 :设置标志位 i (i的左边是比 temp (2) 小的) j(j 的下一个元素是用来和 temp 比较的);
再者 ; j 往后的元素一个一个与 temp 比较 ,如果大于 temp ,j 就再往后找;
当遇到小于 temp 的元素,怎么办呢? 很明显要 i 后移一位再把 i 和 j 里的值交换;
直到结束(末尾);
经过第一次排序后 会得到一个位置 (i+1) 就是 temp(2) 应该在的位置了。
再用递归的方法 把 temp 的前半段 和 后半段 用相同的方法 实现 就会得到 有序的序列了。
简易代码如下:
package AlgorithmTest;
/**
* Created by 10187310 on 11/13/2014.
*/
public class QuickSort {
static void swap(int[] a, int i, int j) {
int tem = a[i];
a[i] = a[j];
a[j] = tem;
}
public static void sort(int[] a, int low, int high) {
if (low < high) {
int temp = a[high];
int i = -1, j = 0;
while (j < high) {
if (a[j] < temp) {
swap(a, a[++i], a[j]);
}
j++;
}
swap(a, a[i + 1], temp);
sort(a, low, i);
sort(a, i + 2, high);
}
}
public static void main(String[] args) {
int[] a = {3, 6, 8, 4, 1, 0, 9, 5, 7, 2};
for (int n : a) {
System.out.print(n + " ");
}
System.out.println();
sort(a, 0, a.length-1);
for (int n : a) {
System.out.print(n + " ");
}
}
}