public class QuickSortJava {
public static void main(String[] args) {
int[] aa = { 0, 49, 38, 65, 97, 76, 13, 27 };
new QuickSort().quickSort(aa, 0, 7);
for (int result : aa) {
System.out.println(result);
}
}
}
class QuickSort {
private int partition(int[] L, int low, int high) {
L[0] = L[low];
int pivotkey = L[low];
while (low < high) {
while (low < high && L[high] >= pivotkey) {
high--;
}
L[low] = L[high];
while (low < high && L[low] <= pivotkey) {
low++;
}
L[high] = L[low];
}
L[low] = L[0];
return low;
}
public void quickSort(int[] L, int low, int high) {
if (low < high) {
Integer pivotloc = partition(L, low, high);
quickSort(L, low, pivotloc - 1);
quickSort(L, pivotloc + 1, high);
}
}
}
下面这种方法简单粗暴
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class QuickSortB {
public static void main(String[] args) {
Integer[] list = { 49, 38, 65, 97, 76, 13, 27 };
List<Integer> items = new ArrayList<Integer>();
for (Integer x : list) {
items.add(x);
}
QuickSortBB qb = new QuickSortBB();
qb.sort(items);
for (Integer x : items) {
System.out.println(x);
}
}
}
class QuickSortBB {
public void sort(List<Integer> items) {
if (items.size() > 1) {
List<Integer> smaller = new ArrayList<>();
List<Integer> same = new ArrayList<>();
List<Integer> larger = new ArrayList<>();
Integer chosenItem = items.get(items.size() / 2);
for (Integer i : items) {
if (i < chosenItem) {
smaller.add(i);
} else if (i > chosenItem) {
larger.add(i);
} else {
same.add(i);
}
}
sort(smaller);
sort(larger);
items.clear();
items.addAll(smaller);
items.addAll(same);
items.addAll(larger);
}
}
}