Java算法----快速排序法

快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。
该方法的基本思想是:

1.先从数列中取出一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。

先列出算法代码:

    /**
     * 快速排序
     * @param arr 要排序的数组
     * @param low 往前
     * @param high 往后
     */
    public void sort(int[] arr, int low, int high) {
        int l = low;
        int h = high;
        int povit = arr[low];
        while (l < h) {
            while (l < h && arr[h] >= povit)
                h--;
            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                l++;
            }
            while (l < h && arr[l] <= povit)
                l++;
            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                h--;
            }
        }
        if (l > low) sort(arr, low, l - 1);
        if (h < high) sort(arr, l + 1, high);
        System.out.println("调用sort方法排序;数组内容:["+printArray(arr)+"],第二个参数:"+low+"第三个参数:"+high);
    }

    /**
     * 进行排序方法测试
     */
    @Test
    public void test() {
        int[] a = new int[] { 9, 15, 21, 12, 3, 11, 4, 32, 27 ,21};
        sort(a, 0, a.length - 1);
    }

    /**
     * 编写一个方法,将数组的内容拼成字符串输出
     * @param arr 要输出的数组
     */
    public String printArray(int[] arr){
        String result = "";
        for(int i=0;i<arr.length;i++){
            result += arr[i]+",";
        }
        return result;
    }

运行后控制台输出:

调用sort方法排序;数组内容:[3,4,9,12,21,11,15,32,27,21,],第二个参数:0第三个参数:0
调用sort方法排序;数组内容:[3,4,9,12,21,11,15,32,27,21,],第二个参数:0第三个参数:1
调用sort方法排序;数组内容:[3,4,9,11,12,21,15,32,27,21,],第二个参数:3第三个参数:3
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,32,27,21,],第二个参数:5第三个参数:5
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:8第三个参数:8
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:7第三个参数:8
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:7第三个参数:9
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:5第三个参数:9
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:3第三个参数:9
调用sort方法排序;数组内容:[3,4,9,11,12,15,21,21,27,32,],第二个参数:0第三个参数:9

前面的都是方法递归调用产生的输出,最后一行为main方法进行调用的sort方法输出的内容

具体意思后续再写出来.

猜你喜欢

转载自blog.csdn.net/qq_26555463/article/details/77448348
今日推荐