快速排序

一.原理

快速排序:幹說原理

  1. 先從數組中選出一個值,作爲權重temp,然後從數組最右邊high(其中一邊都行)開始,向左邊遍歷(記最左邊爲low)
  2. 如果arr[high]比temp大,那麼不管,high繼續向左移動
  3. 如果arr[high]比temp小,那麼此時
  4. arr[low] = arr[high]
  5. 當找到第一個賦值的地方的時候,不在繼續high--;這個時候從左邊開始
  6. 如果arr[low]比temp小,不管,low++
  7. 如果arr[low] 大於temp,那麼第二次交換
  8. arr[high] = arr[low]
  9. 這時暫停low++,又需要回到high--.
  10. 如此交替,直到high和low重合:
  11. 這時high=low
  12. arr[low] = temp;

完成第一輪分組,把比temp大的數放到了右邊,比temp小的數放到了左邊.

再以剛剛的low爲分界,遞歸調用,直到所有元素都滿足小的在左邊,大的在右邊,完成排序

二.圖解

幹說太乾,我們用圖來理解

我們選擇第一個元素爲權重,從右邊開始

接着以43爲分界,前邊從index=0到43的位置,遞歸此方法,後邊亦如此.

java代碼

package sort.quick;

import java.util.Arrays;

/**
 * @description: 快速排序
 * @author:tao
 * @create: 2019-12-28 11:18
 */
public class QuickSort {

    public static void main(String[] args) {
        int []array = {5, 8, 6, 3, 9, 2, 1, 7};
        System.out.println("原數組:" + Arrays.toString(array));
        quickSort(array, 0, array.length - 1);


        System.out.println("排序數組:" + Arrays.toString(array));
    }

    private static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            int index = getEqualIndex(array, low, high);
            quickSort(array, low, index - 1);
            quickSort(array, index + 1, high);
        }

    }

    private static int getEqualIndex(int[] array, int low, int high) {
        int temp = array[low];
        while (low < high) {
            // 後往前
            while (low < high && temp <= array[high]) {
                high--;
            }
            // 交換(temp 比最後大)
            array[low] = array[high];
            while (low < high && temp >= array[low]) {
                low ++;
            }
            array[high] = array[low];
        }
        array[high] = temp;
        return high;
    }


}

原數組:[43, 22, 49, 6, 5, 2, 50, 65]
排序數組:[2, 5, 6, 22, 43, 49, 50, 65]
交換次數=14

發佈了39 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章