快速排序

程序代码:

Robert Sedgewick的版本是最简单易懂的.

 

package ganggong.algorithm.sort;


/**
 * Created by rick on 2015/3/8.
 */
public class QuickSortTest {
    public static void main(String[] args) {
        QuickSortTest sortTest = new QuickSortTest();
        int[] array = {87, 32, 84, 24, 67, 12, 90};
        sortTest.printArray(array);
        System.out.println("begin:");

        sortTest.quickSort(array, 0, array.length - 1);
        sortTest.assertSorted(array);
    }

    private void quickSort(int[] array, int begin, int end) {
        if (begin < end) {
            int j = partition(array, begin, end);
            quickSort(array, begin, j - 1);
            quickSort(array, j + 1, end);
        }
    }

    private int partition(int[] array, int begin, int end) {
        int i = begin;
        int j = end + 1;
        int temp = array[begin];
        while (true) {
            while (i != end && array[++i] < temp) ;
            while (j != begin && array[--j] > temp) ;
            if (i >= j) {
                break;
            }
            exchange(array, i, j);
        }
        exchange(array, begin, j);
        printArray(array);
        return j;
    }

    private void exchange(int[] array, int from, int to) {
        int t = array[from];
        array[from] = array[to];
        array[to] = t;
    }

    private String array2String(int[] array) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i != array.length - 1) {
                sb.append(",");
            }
        }
        sb.append("}");
        return sb.toString();
    }

    private void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + "\t");
        }
        System.out.println();
    }

    private void assertSorted(int[] array) {
        boolean sorted = true;
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                sorted = false;
                break;
            }
        }
        if (!sorted) {
            throw new RuntimeException("Not sorted");
        }
    }
}

 

运行结果:

87    32    84    24    67    12    90   
begin:
12    32    84    24    67    87    90   
12    32    84    24    67    87    90   
12    24    32    84    67    87    90   
12    24    32    67    84    87    90   

你可能感兴趣的:(算法,快速排序)