快速排序的基本思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。
快速排序的示例:
(a)一趟排序的过程:
(b)排序的全过程
把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
基准数:一般指定第一个元素为基准数(任意元素都可以作为基准数)。
//快速排序
public class QuickSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 6, 1, 2, 7, 9, 3, 4, 5, 10, 8 };
quickSort(arr, 0, arr.length - 1);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ",");
}
}
public static void quickSort(int[] arr, int frist, int last) {
if (frist > last)
return;// 递归出口
int i = frist;
int j = last;
int temp = arr[frist]; // 基准数
while (i != j) {
while (arr[j] >= temp && j > i) { // 从右开始寻找小于基准数的元素
j--;
}
while (arr[i] <= temp && i < j) { // 从左开始寻找大于基准数的元素
i++;
}
if (i < j) { // 找到了小于和大于基准数的数
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
if (i == j) { // 找到了中间数,交换基准数与中间数
arr[frist] = arr[i];
arr[i] = temp;
}
// 递归
quickSort(arr, frist, j - 1); //对于数组中小于中间数的部分进行递归排序
quickSort(arr, i + 1, last); //对于数组中大于中间数的部分进行递归排序
}
}