資料結構與演算法之快速排序

某科學的南條發表於2021-01-01

時間複雜度平均O(nlogn)

package com.qiangqiang.sort;

import java.util.Random;

public class QuickSort {

    public static void main(String[] args) {
        Integer[] arr = new Integer[9000000];
        for (int i = 0; i < 9000000; i++) {
            Random random = new Random();
            arr[i] = random.nextInt(99909900);
        }
        long l1 = System.currentTimeMillis();
        sort(arr);
        long l2 = System.currentTimeMillis();
        long l = l2 - l1;
        System.out.println("耗費:" + l + "毫秒");
        for (int i : arr) {
            System.out.print(i + ",");
        }


    }

    //對陣列內元素進行排序
    public static void sort(Comparable[] a) {
        int lo = 0;
        int hi = a.length - 1;
        sort(a, lo, hi);

    }

    //對陣列a中從索引lo到hi之間的元素進行排序
    public static void sort(Comparable[] a, int lo, int hi) {
        if (lo >= hi) {
            return;
        }
        //需要對陣列中lo索引到hi索引的元素進行分組,(左子組和右子組)
        int partition = partition(a, lo, hi);      //返回的是頭元素最為排序基準排序後的索引


        //讓左子組有序,讓右子組有序,那麼整個就有序了
        sort(a, lo, partition - 1);

        sort(a, partition + 1, hi);


    }

    //對陣列a中,從索引lo到索引hi之間的元素進行分組,並返回分組界限對應的索引
    public static int partition(Comparable[] a, int lo, int hi) {
        Comparable key = a[lo];
        int left = lo;
        int right = hi + 1;
        while (true) {

            //先從右往左掃描,移動right指標
            while (comp(key, a[--right])) {
                if (right == lo) {
                    break;
                }
            }

            //從左往右掃描,移動left指標
            while (comp(a[++left], key)) {
                if (left == hi) {
                    break;
                }
            }

            if (left >= right) {
                break;
            } else {
                exchange(a, left, right);
            }


        }
        //交換分界值
        exchange(a, lo, right);


        return right;


    }


    //交換資料
    public static void exchange(Comparable[] a, int i, int j) {
        Comparable temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }


    public static Boolean comp(Comparable a, Comparable b) {
        return a.compareTo(b) < 0;
    }
}

相關文章