快速排序法的思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。
代码如下:
刚开始还是有点难理解的,看了别人的代码,再理解起来就比较容易了,做过小的总结,只为遇见更好的自己。
/**
* 快速排序算法
*
* @author HeHuan
*
*/
public class Quick {
public static void main(String[] args) {
int a[] = { 12, 15, 9, 20, 6, 31, 24 };
quickSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
/**
* 分治法的思想加递归
* @param a 数组
* @param low 数组的最低位
* @param high 数组的最高位
*/
public static void quickSort(int[] a, int low, int high) {
if (low < high) {
int middle = getMiddle(a, low, high);// 获取中间的数值,
quickSort(a, low, middle - 1);// 排序左边的数据
quickSort(a, middle + 1, high);// 排序右边的数据
}
}
private static int getMiddle(int[] a, int low, int high) {
int temp = a[low];// 取数组的第一个值为初始值,与最右边的值进行对比
while (low < high) {
while (temp < a[high] && low < high) {// 如果小于最后边的值
high--;
}
a[low] = a[high];// 如果temp大于右边的值,填坑到low的位置,high的位置空了出来
while (temp > a[low] && low < high) {// 如果大于左边的值
low++;
}
a[high] = a[low];// 如果temp小于左边的值,高位被填坑,low位又被腾出来
}
a[low] = temp;//最后把temp值给low位,位置也就固定了,不会再改变,这时候low = high
return high;
}
}