简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test2;
public class Quick {
public static void main(String[] args) {
Comparable[] a = { 5, 3, 1, 2, 4 };
sort(a);
show(a);
}
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
private static void sort(Comparable[] a) {
sort(a, 0, a.length - 1);
}
private static void sort(Comparable[] a, int lo, int hi) {
if (lo >= hi) {
return;
}
int j = partition(a, lo, hi);
sort(a, lo, j - 1);
sort(a, j + 1, hi);
}
private static int partition(Comparable[] a, int lo, int hi) {
int i = lo;
int j = hi + 1;
while (true) {
while (less(a, ++i, lo)) {
if (i == hi) {
break;
}
}
while (less(a, lo, --j)) {
if (j == lo) {
break;
}
}
if (i >= j) {
break;
}
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean less(Comparable[] a, int i, int j) {
return a[i].compareTo(a[j]) < 0;
}
}
输出
1 2 3 4 5
Happy learning !!