快速排序

来源:互联网 发布:花生壳域名ip解析失败 编辑:程序博客网 时间:2024/06/07 05:54

一.  快速排序的基本思想

快速排序使用分治的思想,通过一趟排序将待排序列分割成两部分,其中一部分记录的关键字均比另一部分记录的关键字小。之后分别对这两部分记录继续进行排序,以达到整个序列有序的目的。


二.  快速排序的三个步骤

1) 选择基准:在待排序列中,按照某种方式挑出一个元素,作为 “基准”(pivot);

2) 分割操作:以该基准在序列中的实际位置,把序列分成两个子序列。此时,在基准左边的元素都比该基准小,在基准右边的元素都比基准大;

3) 递归地对两个序列进行快速排序,直到序列为空或者只有一个元素;

代码:

private static void quickSort2(int[] a, int low, int height) {if (low < height) {int l = low;int h = height;// 选取固定基准源int lvalue = a[l];while (l < h) {// 第一次右向左的排序while (l < h && a[h] >= lvalue)h--;if (l < h) {a[l] = a[h];l++;}// 第二次左向右的排序while (l < h && a[l] <= lvalue)l++;if (l < h) a[h--] = a[l];}a[l] = lvalue;System.out.println(Arrays.toString(a));System.out.println("l=" + l + " h=" + h + " value=" + lvalue);quickSort2(a, low, l - 1);quickSort2(a, h + 1, height);}}


1 0
原创粉丝点击