二十、快速排序演算法——JAVA實現(遞迴)

Hro發表於2019-01-15

一、快速排序原理:
   首先找到一個基準,一般以第一個元素作為基準(pivot),然後先從右向左搜尋, 如果發現比pivot小,則和pivot交換,然後從左向右搜尋,如果發現比pivot大,則和pivot交換,以此迴圈,一輪迴圈完後,pivot左邊的都比它小,而右邊的都比它大, 此時pivot的位置就是排好序後的最終位置,此時pivot將陣列劃分為左右兩部分,每部分繼續上面的排序操作(推薦遞迴方式)。

二、程式碼實現:
   排序前陣列為:[1, 3, 2, 8, 5, 10, 22, 11, 2, 18]
   排序後陣列為:[1, 2, 2, 3, 5, 8, 10, 11, 18, 22]

/**
 * 快速排序
 *
 * @author wxf
 * @date 2019/1/14 9:22
 **/
public class FastSort {

    public static void main(String[] args) {
        int[] a = {1, 3, 2, 8, 5, 10, 22, 11, 2, 18};
        quickSort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    /**
     * 快速排序
     *
     * @param arr  陣列
     * @param low  基準數位置
     * @param high 陣列長度
     */
    private static void quickSort(int[] arr, int low, int high) {
        int start = low;
        //arr[low]為基準數
        int key = arr[low];
        int end = high;
        while (start < end) {
            //右->左查詢,找到比基準數小的值則交換位置
            while (arr[end] >= key && end > start) {
                end--;
            }
//            if (arr[end] < key) {
//                int temp = arr[end];
//                arr[end] = key;
//                arr[low] = temp;
//            }
            arr[start] = arr[end];
            //左->右查詢,找到比基準數大的值則交換位置
            while (arr[start] <= key && end > start) {
                start++;
            }
//            if (arr[start] > key) {
//                int temp = arr[start];
//                arr[start] = key;
//                arr[end] = temp;
//            }
            arr[end] = arr[start];
        }
        arr[start] = key;
        //遞迴
        if (start > low) {
            quickSort(arr, low, start - 1);
        }
        if (end < high) {
            quickSort(arr, start + 1, high);
        }
    }
}
複製程式碼

相關文章