快速排序

各种时间复杂度总结:
default

快速排序工作原理:
  通过一趟排序将待排记录分隔成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序。

时间复杂度:
  最差时间复杂度 | O(n^2)

大部分情况下都比其他排序算法要快

package com.core.test.sort;

public class QuickSort {
    public static void main(String[] args) {
        int[] a = {1, 5, 7, 3, 2, 8, 4, 6};
        quickSort(a, 0, 7);//第一次选中第一个元素作为基准
        for (int b : a) {
            System.out.print(b + " ");
        }
    }

    private static void quickSort(int[] arr, int low, int high) {
        if (low < high) {//跳出循环回调的关键
            int privotLoc = partition(arr, low, high);
            quickSort(arr, low, privotLoc - 1);
            quickSort(arr, privotLoc + 1, high);
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int privotKey = arr[low];
        /*
        * 每次都是选中被分割的数组的第一个元素为基准
        * 则从high开始查找比基准小的然后交换 然后从low查找比基准大的 交换
        * 最后返回值low就是基准当前所在位置
        * */
        while (low < high) {
            while (low < high && arr[high] >= privotKey)
                high--;
            swap(arr, low, high);
            while (low < high && arr[low] <= privotKey)
                low++;
            swap(arr, low, high);
        }
        return low;
    }

    private static void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
原文地址:https://www.cnblogs.com/programmer1/p/7994101.html