2020-04-10快速排序的Java实现


package hxy.bytecode.algorithm.sort;

/**
 * @author eric
 * @program bytecode
 * @description 快速排序
 * @date 2020/4/10
 */
public class QuickSort2 {

    public void quickSort(int[] a, int low, int high) {
        int low1 = low;
        int high1 = high;

        if (low >= high) {
            return;
        }

        // 选取第一个为基线
        int index = a[low];
        while (low < high) {
            while (low < high && index < a[high]) {
                high--;
            }
            if (low < high) {
                a[low] = a[high];
                low++;
            }
            while (low < high && index > a[low]) {
                low++;
            }
            if (low < high) {
                a[high] = a[low];
                high--;
            }
        }
        // 找到自己的中间位置
        a[low] = index;

        quickSort(a, low1, low - 1);
        quickSort(a, low + 1, high1);
    }


    public static void main(String[] args) {
        int[] a = {1, 2, 5, 4, 7, 9, 0, 8, 3, 6};

        new QuickSort2().quickSort(a, 0, a.length - 1);

        for (int i = 0; i < a.length; i++) {

            System.out.print(a[i] + "\t");

        }
    }
}

结果如下:


快速排序结果

推荐阅读更多精彩内容