一般情况下O(n*logn) 比一般排序算法都要快
最坏情况, 在数组已经排序好, 接近排序好, 需要O(n*n).
平均时间复杂度也是O(n*logn)
Pseudocode:
quickSort(array, left, right)
{
index = partion(array, left, right);
if (left < index) { quickSort(array, left, index); }
if (index < right) { quickSort(array, index, right); }
}
partion(array, left, right)
{
middle as pivot;
larger than pivot, move to the right part;
smaller than pivot, move to the left part;
return the partion index of two pars;
}
Java:
package ncku.cdc.sorting;
import java.util.Random;
public class QuickSort {
private int[] sequence;
public QuickSort(int size, int range) {
sequence = new int[size];
Random rand = new Random();
for (int i = 0; i < size; i++) {
sequence[i] = rand.nextInt(range);
}
}
public static void main(String[] args) {
int size = Integer.valueOf(args[0]);
int range = Integer.valueOf(args[1]);
QuickSort quick = new QuickSort(size, range);
System.out.println("before quickSort:");
SortingTools.validation(quick.getSequence(), 0);
quick.quickSort(quick.getSequence(), 0, size - 1);
System.out.println("after quickSort:");
SortingTools.validation(quick.getSequence(), 0);
}
public void quickSort(int[] seq, int left, int right) {
int index = partition(seq, left, right);
if (left < index - 1) { quickSort(seq, left, index - 1); }
if (index < right) { quickSort(seq, index, right); }
}
private int partition(int[] arr, int left, int right) {
int i = left;
int j = right;
int pivot = arr[(left + right) >> 1];
while (i <= j) {
while (arr[i] < pivot) { i++; }
while (arr[j] > pivot) { j--; }
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
return i;
}
private void swap(int[] arr, int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public int[] getSequence() {
return sequence;
}
}
程序输入: 35 200. 表示随机生成长度为35, 每个数字范围从[0, 200)的数组.
程序输出:
before quickSort:
76 34 114 62 175 96 96 59 102 191 8 133 13 0 9 198 10 132 162 175 103 136 19 32 83 107 93 21 165 152 175 3 46 175 94
after quickSort:
0 3 8 9 10 13 19 21 32 34 46 59 62 76 83 93 94 96 96 102 103 107 114 132 133 136 152 162 165 175 175 175 175 191 198