Java数据结构–快速排序
定义:
快速排序由C. A. R. Hoare在1960年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列
排序类
public class Quick {
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
public static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void sort(Comparable[] a) {
int low = 0;
int high = a.length - 1;
sort(a, low, high);
}
public static void sort(Comparable[] a, int low, int high) {
if (high <= low) {
return;
}
int partition = partition(a, low, high);
sort(a, low, partition - 1);
sort(a, partition + 1, high);
}
public static int partition(Comparable[] a, int low, int hight) {
Comparable key = a[0];
int left = low;
int right = hight + 1;
while (true) {
//先右到左
while (less(key, a[--right])) {
if (right == low)
break;
}
while (less(a[++left], key)) {
if (left == hight)
break;
}
if (left >= right)
break;
else
exch(a, left, right);
}
exch(a, low, right);
return right;
}
}
测试类
public class QuickTest {
public static void main(String[] args) {
Integer[] arr = {55, 11, 2, 4, 32, 6, 99};
Quick.sort(arr);
System.out.println(Arrays.toString(arr));
}
}