快速排序

快速排序的基本思想

         通过一趟排序将待排序记录分割成独立的两部分,其中一部分关键字均比另一部分关键字小;

        分别对这两部分继续进行排序,直到整个序列有序。

 

快速排序的示例

(a)一趟排序的过程:

(b)排序的全过程

  把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。

 

代码自己实现的:

public class 快排 {
    public static void main(String[] args) {
        int[] test = {3, 1, 6, 9, 5, 334, 7, 8, 34, 235, 64, 78};
        quickSort(test, 0, test.length - 1);
        for (int i : test) {
            System.out.print(i + " ");
        }
    }

    public static void quickSort(int[] list, int low, int high) {
        if (low < high) {
            int index = partition(list, low, high);
            quickSort(list, low, index - 1);
            quickSort(list, index + 1, high);
        }
    }

    private static int partition(int[] list, int low, int high) {
        int j = high;
        int i = low;
        int index = list[low];
        while (i < j) {
            while (list[j] > index) j--;
            while (list[i] < index) i++;
            swap(list,i,j);
        }
        return i;
    }

    private static void swap(int[] list, int a, int b) {
        int tmp = list[a];
        list[a] = list[b];
        list[b] = tmp;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值