快速排序

来源:互联网 发布:iphone7p淘宝店铺 编辑:程序博客网 时间:2024/06/16 12:26

交换排序–快速排序

基本思想

通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序

其一趟排序过程:

这里写图片描述

整个排序过程

整个排序过程

package wj.dev.test;public class Main {    public static void main(String[] args) {        int a[] = { 3, 1, 5, 7, 2, 4, 9, 6, 10, 8 };        System.out.print("初始值:");        print(a);        quickSort(a, 0, 9);        System.out.print("结果:");        print(a);    }    public static void print(int[] a) {        for (int i = 0; i < a.length; i++)            System.out.print(a[i] + " ");        System.out.println();    }    /**     * 进行一次排序,返回基准元素在排序后所在的位置     *      * @param a     * @param low     *            左边索引     * @param high     *            右边索引     * @return     */    public static int partition(int a[], int low, int high) {        int key = a[low];// 取第一个元素为基准元素        while (low < high) {            // 从后面往前面遍历,直至基准元素大于后面的元素为止            while (low < high && key <= a[high])                high--;            a[low] = a[high];            // 从前面往后面遍历,直至基准元素小于前面的元素为止            while (low < high && key >= a[low])                low++;            a[high] = a[low];        }        a[low] = key;        print(a);        return low;    }    public static void quickSort(int a[], int low, int high) {        if (low < high) {            int privotLoc = partition(a, low, high); // 将表一分为二            quickSort(a, low, privotLoc - 1); // 递归对低子表递归排序            quickSort(a, privotLoc + 1, high); // 递归对高子表递归排序        }    }}

通常,快速排序被认为是,在所有同数量级(O(nlogn))的排序方法中,其平均性能最好。但是,若初始记录序列按关键字有序或基本有序时,快速排序将退化为起泡排序,其时间复杂度为O(n^2)。为改进之,通常依“三者取中”的法则来选取枢轴记录,即将排序区间的两个端点与中点三个记录关键码居中的调整为支点记录。

0 0
原创粉丝点击