/**
* 快速排序
*
* @param a
*
*/
public static void quickSort(int[] a) {
quickSortA(a, 0, a.length - 1);
}
private static void quickSortA(int[] a, int begin, int end) {
if (begin < end) {
int pivot = partition(a, begin, end);
quickSortA(a, begin, pivot - 1);
quickSortA(a, pivot + 1, end);
}
}
private static int partition(int[] a, int begin, int end) {
int i = begin - 1;
for (int j = begin; j < end; j++) {
if (a[j] < a[end]) {
swap(a, ++i, j);
}
}
swap(a, ++i, end);
return i;
}
/**
* 非递归快速排序
*
* @param a
*/
public static void quickSortNR(int[] a) {
int begin = 0;
int end = a.length - 1;
int pivot;
LinkedList<Integer> queue = new LinkedList<Integer>(); // 使用队列来模拟树的遍历
queue.add(begin);
queue.add(end);
while (!queue.isEmpty()) {
begin = queue.poll();
end = queue.poll();
pivot = partition(a, begin, end);
if (begin < pivot) {
queue.add(begin);
queue.add(pivot - 1);
}
if (end > pivot) {
queue.add(pivot + 1);
queue.add(end);
}
}
}
快速排序
最新推荐文章于 2021-03-08 20:42:51 发布