快速排序簡介以及代碼

1.原理:
(1)首先找到一個基準(一般情況以數組最左邊的元素爲基準)
(2)在每一輪遞歸循環中不斷調換左右元素,找到基準的準確位置
(3)遞歸循環第(1)、(2)步。知道左、右元素索引位置相同。

2.時間複雜度O (nlogn)

3.代碼:

public class QuickSort{
    public static int [] nums = {20, 33, 12, 4, 43434, 231, 44, 1, 1, 443, 1, 33, 2, 45,2};

    public static void main(String [] args){
    quickSort(0, nums.length-1);
    for(int i : nums) System.out.println(i);
    }

    public static void quickSort(int left, int right){
    if(left >= right) return;
    int base = nums[left];
    int l = left;
    int r = right;

    while(l < r){
        while(nums[r] >= base && l < r) r--;
        while(nums[l] <= base && l < r) l++;
        if(l < r) changeArray(l , r);
    }

    nums[left] = nums[l];
    nums[l] = base;
    quickSort(left, l-1);
    quickSort(l+1, right);
    }

    public static void changeArray(int l, int r){
    int temp = nums[l];
    nums[l] = nums[r];
    nums[r] = temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章