第七章 快速排序

package chap07_Quick_Sort;

import static org.junit.Assert.*;

import java.util.Arrays;

import org.junit.Test;

public class SortAlgorithms {
    /**
     * 快速排序算法
     * 
     * @param n
     */
    static void quickSort(int[] n) {
        int from = 0;
        int to = n.length;
        // quickSort(n, from, to);
        quickSort1(n, from, to);

    }

    /**
     * 快速排序的递归实现,将n从start到end之间的数字排序(不包括end)
     * 
     * @param n
     * @param start
     * @param end
     */
    static protected void quickSort(int[] n, int start, int end) {
        if (start < end - 1) {
            int a;
            a = partition(n, start, end);

            quickSort(n, start, a);
            quickSort(n, a, end);
        }
    }

    /**
     * 快速排序的迭代实现
     * 
     * @param n
     * @param start
     * @param end
     */
    static protected void quickSort1(int[] n, int start, int end) {
        int a = partition(n, start, end);
        int b = a;
        while (start < a - 1) {
            a = partition(n, start, a);
        }
        while (b < end - 1) {
            b = partition(n, b, end);
        }
    }

    /**
     * 分割(快速排序中对数组的分割)
     * 
     * @param n
     * @param start
     * @param end
     * @return
     */
    protected static int partition(int[] n, int start, int end) {
        int p = end - 1;
        int s = start;// s位于大于a[p]和小于a[p]之间的位置
        int tmp;
        for (int i = start; i < end; i++) {
            if (n[i] < n[p]) {
                tmp = n[i];
                n[i] = n[s];
                n[s] = tmp;
                s++;
            }
        }
        {
            tmp = n[s];
            n[s] = n[p];
            n[p] = tmp;
        }
        return s;
    }

    @Test
    public void testName() throws Exception {
        int[] a = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };
        // System.out.println(Arrays.toString(a));
        // partition(a, 0, 12);
        quickSort(a);
        System.out.println(Arrays.toString(a));
    }
}
原文地址:https://www.cnblogs.com/xiaojintao/p/3780584.html