copy了个程序,这个算法用了递归。
package com.test.convert;
public class QuickSort {
public static void sort(Comparable[] data) {
sort(data, 0, data.length - 1);
}
public static void sort(Comparable[] data, int low, int high) {
Comparable pivot = data[low];
int i = low;
int j = high;
if (low < high) {
while (i < j) {
while (i < j && data[j].compareTo(pivot) > 0) {
j--;
}
if (i < j) {
data[i] = data[j];
i++;
}
while (i < j && data[i].compareTo(pivot) < 0) {
i++;
}
if (i < j) {
data[j] = data[i];
j--;
}
}
}
data[i] = pivot;
if (low < i - 1)
sort(data, low, i - 1);
if (i + 1 < high)
sort(data, i + 1, high);
}
public static void main(String[] args) {
Comparable[] c = { 4, 9, 23, 1, 45, 27, 5, 2 };
QuickSort.sort(c);
for (Comparable data : c) {
System.out.print(data+" ");
}
}
}