import edu.princeton.cs.algs4.StdRandom;
public class Quick {
private Quick() { }
public static void sort( Comparable[] a ) {
StdRandom.shuffle(a);//随机化初始数组
sort(a, 0, a.length - 1);
assert isSorted(a);
}
private static void sort(Comparable[] a, int low, int high) {
if (high <= low)
return;
int i = partition(a, low, high);
sort(a, low, i-1);
sort(a, i + 1, high);
}//无重复数据时
private static int partition(Comparable[] a, int low, int high) {
Comparable sentry = a[low];
int i = low+1;
int j = high;
while (i < j) {
while (less(a[++i], sentry))
; //i<j 的判断条件确保了i不会越界,所以无需再判断
while (less(sentry, a[--j]))
;//a[j]一定大于sentry,无需判断越界
exch(a, i, j);
}
exch(a, low ,j);
return j;
}
private static void sort2(Comparable[] a, int low, int high) {
if (high <= low)
return;
int i = low+1;
int left = low;
int right = high;
Comparable sentry = a[low];
while (i <= right) {
if (less(a[i], sentry)) {
exch(a, i++, left++);//简写
} else if (less(sentry, a[i])) {
exch(a, i ,right--);
}
else i++;
}
sort2(a, low, left-1);
sort2(a, right + 1, high) ;
}//有重复数据时
private static boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
算法 2.3节 有重复数据和没有的快速排序
最新推荐文章于 2023-04-11 08:27:12 发布