Fork me on GitHub

QuickSort

  1. 快排原理及方法

数学之美番外篇:快排为什么那样快 -BY 刘未鹏 – JUNE 13, 2008
白话经典算法系列之六 快速排序 快速搞定 -morewindows 经典算法系列

  1. Java 源代码
public class QuickSort {
    public static void main(String[] args) {
        int[] num = new int[10];
        for (int i = 0; i < num.length; i++)
            num[i] = (int) (Math.random() * 100);

        for (int n : num)
            System.out.print(n + " ");
        System.out.println();

        quickSort(num, 0, num.length - 1);
        for (int i : num)
            System.out.print(i + " ");
    }
    public static void quickSort(int[] num, int l, int r) {
        if (l < r) {
            int key = num[l];
            System.out.println("The key:" + num[l]);
            int i = l;
            int j = r;

            while (i < j) {
                while (num[j] > key && i < j)
                    j--;
                if (i < j)
                    num[i++] = num[j];

                while (num[i] < key && i < j)
                    i++;
                if (i < j)
                    num[j--] = num[i];
            }
            num[i] = key;
            for (int n : num)
                System.out.print(n + " ");
            System.out.println();
            quickSort(num, l, i - 1);
            quickSort(num, i + 1, r);
        }
    }
}

posted @ 2016-10-16 21:37  morethink  阅读(214)  评论(0编辑  收藏  举报