快速排序

基本思想:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

设要排序的数组是A[0]……A[N-1],首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法,也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。

一趟快速排序的算法是:
1)设置两个变量i、j,排序开始的时候:i=0,j=N-1;
2)以第一个数组元素作为关键数据,赋值给key,即key=A[0];
3)从j开始向前搜索,即由后开始向前搜索(j–),找到第一个小于key的值A[j],将A[j]和A[i]互换;
4)从i开始向后搜索,即由前开始向后搜索(i++),找到第一个大于key的A[i],将A[i]和A[j]互换;
5)重复第3、4步,直到i=j; (3,4步中,没找到符合条件的值,即3中A[j]不小于key,4中A[i]不大于key的时候改变j、i的值,使得j=j-1,i=i+1,直至找到为止。找到符合条件的值,进行交换的时候i, j指针位置不变。另外,i==j这一过程一定正好是i+或j-完成的时候,此时令循环结束)。

给定数组a[8]={2,8,7,1,3,5,6,4};其排序过程表示为:
这里写图片描述

Java代码:

import java.util.Arrays;
import java.util.Comparator;

public class QuickSorter {
    private QuickSorter() {}

    public static void sort(int[] a) {
        sort(a, 0, a.length);
    }

    public static void sort(int[] a, int fromIndex, int toIndex) {
        if (toIndex - fromIndex > 1) {
            int q = partition(a, fromIndex, toIndex);

            sort(a, fromIndex, q-1 ); // 注意这里是q-1而不是q,a[q]=pivot可以不用它算进来排序,
                                      // 相反算进来会发生死递归,考虑对数组[2,3]返回q=2,会循环调用sort(a, 0, 2)。
            sort(a, q, toIndex);
        }
    }

    private static int partition(int[] a, int fromIndex, int toIndex) {
        int lastIndex = toIndex - 1;
        int pivot = a[lastIndex];
        int i = fromIndex;
        for (int j = fromIndex; j < lastIndex; j++) {
            // 循环不变式:(跟教材上有所不同)
            //      a[fromIndex..i) <= pivot
            //      a[i..j) > pivot
            //      a[toIndex-1] = pivot
            if (a[j] <= pivot) {
                swap(a, i++, j);
            }
        }
        swap(a, i, lastIndex);

        return i + 1;
    }

    /**
     * 见思考题7-1:使用HOARE_PARTITION
     */
    public static void sort2(int[] a) {
        sort2(a, 0, a.length);
    }
    public static void sort2(int[] a, int fromIndex, int toIndex) {
        if (toIndex - fromIndex > 1) {
            int q = partition2(a, fromIndex, toIndex);

            sort(a, fromIndex, q ); // 注意这里是q
            sort(a, q, toIndex);
        }
    }

    /*
     * HOARE_PARTITION分治法。
     * 注意:这里之所以不会出现超出数组边界的访问,是因为第一次循环结束是必有a[fromIndex]<=pivot,a[toIndex-1]>=pivot
     */
    private static int partition2(int[] a, int fromIndex, int toIndex) {
        int pivot = a[fromIndex];
        int i = fromIndex - 1;
        int j = toIndex;
        while (true) {
            /* 循环不变式
                    a[fromIndex..i] <= pivot
                    a[j..toIndex) >= pivot */
            while (a[--j] > pivot) continue;
            while (a[++i] < pivot) continue;
            if (i < j) {
                swap(a, i, j);
            } else {
                return i;
            }
        }
    }

    public static void sort(Object[] a) {
        sort(a, 0, a.length);
    }

    public static void sort(Object[] a, int fromIndex, int toIndex) {
        if (toIndex - fromIndex > 1) {
            int q = partition(a, fromIndex, toIndex);

            sort(a, fromIndex, q-1 );
            sort(a, q, toIndex);
        }
    }

    @SuppressWarnings("unchecked")
    private static int partition(Object[] a, int fromIndex, int toIndex) {
        int lastIndex = toIndex - 1;
        Object pivot = a[lastIndex];
        int i = fromIndex;
        for (int j = fromIndex; j < lastIndex; j++) {
            if (((Comparable)a[j]).compareTo(pivot) <= 0) {
                swap(a, i++, j);
            }
        }

        swap(a, i, lastIndex);

        return i + 1;
    }

    public static <T> void sort(T[] a, Comparator<? super T> c) {
        sort(a, 0, a.length, c);
    }

    public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) {
        if (toIndex - fromIndex > 1) {
            int q = partition(a, fromIndex, toIndex, c);

            sort(a, fromIndex, q-1, c);
            sort(a, q, toIndex, c);
        }
    }

    private static <T> int partition(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) {
        int lastIndex = toIndex - 1;
        T pivot = a[lastIndex];
        int i = fromIndex;
        for (int j = fromIndex; j < lastIndex; j++) {
            if (c.compare(a[j], pivot) <= 0) {
                swap(a, i++, j);
            }
        }
        swap(a, i, lastIndex);

        return i + 1;
    }


    private static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; }
    private static void swap(Object[] a, int i, int j) { Object temp = a[i]; a[i] = a[j]; a[j] = temp; }

    public static void main(String[] args) {
        int[] a = {5, 3, 2};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[]{5, 2, 3};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[] {2, 3, 5};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[] {2, 3};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[] {3, 2};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[] {3, 3};
        sort2(a);
        System.out.println(Arrays.toString(a));

        a = new int[] {3, 3, 3};
        sort2(a);
        System.out.println(Arrays.toString(a));

        Integer[] a2 = {3, 5, 2, 1, 21, 7};
        sort(a2);
        System.out.println(Arrays.toString(a2));

        a2 = new Integer[]{3, 5, 2, 1, 21, 7};
        sort(a2, new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        System.out.println(Arrays.toString(a2));
    }
}

注:代码来自算法导论的Java实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值