/***
*
* @author xiaoo_gan
* 快速排序
*
*
* 测试:
* 第一种partition
* 排序 20000000 个数, 快速排序用时: 11.58600 秒
* 排序 50000000 个数, 快速排序用时: 37.75700 秒
*
*
* 第二种partition
* 排序 20000000 个数, 快速排序用时: 12.05800 秒
*
*/
public class Quick {
//第一种排序
public static void sort(Comparable[] a) {
//StdRandom.shuffle(a);
sort(a, 0, a.length -1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if(hi <= lo)
return;
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
//partiton函数一
private static int partition(Comparable[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
Comparable value = a[lo];
while(true) {
while(less(a[++i], value))
if (i == hi) {
break;
}
while(less(value, a[--j]))
if (j == lo) {
break;
}
if (i >= j) {
break;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
private static boolean less(Comparable a, Comparable b) {
return (a.compareTo(b) < 0);
}
//第二种排序
public static void sort1(Comparable[] a) {
//StdRandom.shuffle(a);
sort1(a, 0, a.length -1);
}
private static void sort1(Comparable[] a, int lo, int hi) {
if(hi <= lo)
return;
int j = partition1(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
//partiton函数二 来自算法导论
private static int partition1(Comparable[] a, int lo, int hi) {
Comparable x = a[hi];
int i = lo - 1;
for (int j = lo; j <= hi - 1; j++) {
if (less1(a[j], x)) {
i ++;
exch(a, i, j);
}
}
exch(a, i + 1, hi);
return i + 1;
}
private static boolean less1(Comparable a, Comparable b) {
return (a.compareTo(b) <= 0);
}
private static void exch(Comparable[] a, int i, int j) {
Comparable swap = a[i];
a[i] = a[j];
a[j] = swap;
}
public static boolean isSorted(Comparable[] a) {
for (int i = 0; i < a.length - 1; i++) {
if(!less(a[i], a[i+1]))
return false;
}
return true;
}
private static void print(Boolean isSorted, Comparable[] a) {
if (isSorted) {
StdOut.println("after sorting :");
} else {
StdOut.println("before sorting :");
}
for (int i = 0; i < a.length; i++) {
if ((i % 10) == 0) {
if(i != 0)
StdOut.println();
StdOut.print("\t");
}
StdOut.print("\t" + a[i]);
}
StdOut.println();
}
public static void main(String[] args) {
int M = 20000000;
Double[] a = new Double[M];
for (int i = 0; i < M; i++) {
a[i] = StdRandom.uniform();
}
//String[] a = {"S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E"};
//print(false, a);
Stopwatch timer = new Stopwatch();
sort1(a);
double elapsedTime = timer.elapsedTime();
//print(true, a);
if(isSorted(a))
System.out.printf("排序 %d 个数, 快速排序用时: %.5f 秒", a.length, elapsedTime);
}
}
[算法之排序]快速排序算法(java实现)
最新推荐文章于 2021-02-12 18:49:57 发布