1. 程式人生 > 實用技巧 >最長迴文子串與最長迴文子序列(dp,Manacher)

最長迴文子串與最長迴文子序列(dp,Manacher)

歸併排序

歸併排序介紹:歸併排序(MERGE-SORT)是利用歸併的思想實現的排序方法,該演算法採用經典的分治divide-and-conquer)策略(分治法將問題(divide)成一些小的問題然後遞迴求解,而(conquer)的階段則將分的階段得到的各答案"修補"在一起,即分而治之)

 /**
     * 分解
     *
     * @param arr   陣列
     * @param left  左邊起點
     * @param right 右邊終點
     * @param temp  轉換陣列
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        int mid = (left + right) / 2;
        if (left < right) {
            //左分
            mergeSort(arr, left, mid, temp);
            //右分
            mergeSort(arr, mid + 1, right, temp);
            //左右合併
            merge(arr, left, mid, right, temp);

        }
        //合併

    }

    /**
     * 合併
     *
     * @param arr   陣列
     * @param left  左邊開始
     * @param mid   右邊開始
     * @param right 右邊結束
     * @param temp  轉換陣列
     */

    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {

        int t = 0;//臨時陣列開始下標
        int leftIndex=left;//左邊開始下標
        int midIndex=mid+1;//右邊開始下標
        while (leftIndex <= mid&&midIndex<=right) {
            //兩邊進行比較 小的放入臨時陣列
            if (arr[leftIndex] <= arr[midIndex]) {
                temp[t] = arr[leftIndex];
                t++;
                leftIndex++;
            } else {
                temp[t] = arr[midIndex];
                t++;
                midIndex++;
            }
        }
        //右邊全部比較完畢左邊有剩餘
        while (leftIndex<=mid){
            temp[t] = arr[leftIndex];
            t++;
            leftIndex++;
        }
        //左邊全部比較完畢右邊有剩餘
        while (midIndex<=right){
            temp[t] = arr[midIndex];
            t++;
            midIndex++;
        }

        //全部比較完畢 從臨時陣列放入到arr中
        t=0;
        for (int i=left;i<=right;i++){
            arr[i]=temp[t++];
        }


    }