码迷,mamicode.com
首页 > 其他好文 > 详细

排序之 快速排序

时间:2014-08-07 18:05:30      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   os   io   strong   

采用算法导论上的实现方式,用java实现。

快排算法核心的部分便是partition过程,这里的partition采取最后一个元素作为pivot,i和j两个指针都从头向后扫描,如下图所示,数组被分为4个部分。

 

bubuko.com,布布扣

算法执行的过程:

bubuko.com,布布扣

 

代码实现:

import java.util.Arrays;

public class MySort {

    public static void quickSort(int[] a) {
        qSort(a, 0, a.length - 1);
    }

    private static void qSort(int[] a, int p, int r) {
        if (p < r) {
            int q = partition(a, p, r);
            qSort(a, p, q - 1);
            qSort(a, q + 1, r);
        }
    }

    private static int partition(int[] a, int p, int r) {
        int x = a[r];
        int i = p - 1;
        int j = p;
        for (j = p; j < r; j++) {
            if (a[j] <= x) {
                i++;
                swap(a, i, j);
            }
        }
        swap(a, i + 1, r);

        return i + 1;
    }

    private static void swap(int[] a, int i, int j) {
        if (i != j) {
            int tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }

    }

    public static void main(String[] args) {
        int[] a = { 2, 8, 7, 1, 3, 5, 6, 4 };
        System.out.println(Arrays.toString(a));
        quickSort(a);
        System.out.println(Arrays.toString(a));

    }

}

 

 

正确性证明:

bubuko.com,布布扣

 

排序之 快速排序,布布扣,bubuko.com

排序之 快速排序

标签:style   blog   http   color   java   os   io   strong   

原文地址:http://www.cnblogs.com/jdflyfly/p/3897331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!