快速排序的基本思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分关键字均比另一部分关键字小;
分别对这两部分继续进行排序,直到整个序列有序。
快速排序的示例:
(a)一趟排序的过程:
(b)排序的全过程
把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
代码自己实现的:
public class 快排 {
public static void main(String[] args) {
int[] test = {3, 1, 6, 9, 5, 334, 7, 8, 34, 235, 64, 78};
quickSort(test, 0, test.length - 1);
for (int i : test) {
System.out.print(i + " ");
}
}
public static void quickSort(int[] list, int low, int high) {
if (low < high) {
int index = partition(list, low, high);
quickSort(list, low, index - 1);
quickSort(list, index + 1, high);
}
}
private static int partition(int[] list, int low, int high) {
int j = high;
int i = low;
int index = list[low];
while (i < j) {
while (list[j] > index) j--;
while (list[i] < index) i++;
swap(list,i,j);
}
return i;
}
private static void swap(int[] list, int a, int b) {
int tmp = list[a];
list[a] = list[b];
list[b] = tmp;
}
}