• 分治法


    package alg;
    
    import java.util.Arrays;
    
    /**
     * 分治法
     * Created by dinghaiyun on 2017/9/4.
     */
    public class DivideAndConquer {
        public static void main(String[] args) {
    
            int[] arr = new int[]{5, 2, 4, 7, 1, 3, 2, 6};
    
            mergeSort(arr, 0, arr.length - 1);
    
            System.out.println(" divide and conquer result:  " + Arrays.toString(arr));
    
        }
    
        private static void mergeSort(int[] arr, int p, int r) {
            if (p < r) {
                int q = (p + r) / 2;
    
                mergeSort(arr, p, q);
    
                mergeSort(arr, q + 1, r);
    
                merge(arr, p, q, r);
    
                System.out.println("mereResult : " + Arrays.toString(arr));
            }
    
        }
    
        private static int[] merge(int[] arr, int p, int q, int r) {
            int leftLen = q - p + 1;
            int rightLen = r - (q + 1) + 1;
            int[] arrLeft = new int[leftLen];
            int[] arrRight = new int[rightLen];
            for (int i = p; i <= q; i++) {
                arrLeft[i - p] = arr[i];
            }
            for (int i = q + 1; i <= r; i++) {
                arrRight[i - (q + 1)] = arr[i];
            }
    
            System.out.println("left:" + Arrays.toString(arrLeft) + ", right:" + Arrays.toString(arrRight));
            int i = 0, j = 0;
            int index = p;
            while (i < leftLen && j < rightLen) {
                if (arrLeft[i] < arrRight[j]) {
                    arr[index] = arrLeft[i];
                    i++;
                } else if (arrLeft[i] > arrRight[j]) {
                    arr[index] = arrRight[j];
                    j++;
                } else {
                    arr[index] = arrLeft[i];
                    arr[index + 1] = arrRight[j];
                    i++;
                    j++;
                    index++;
                }
                index++;
            }
    
            int increasement = 0;
            if (i != leftLen) {
                for (; i < leftLen; i++) {
                    arr[index + increasement] = arrLeft[i];
                    increasement++;
                }
    
            } else {
                for (; j < rightLen; j++) {
                    arr[index + increasement] = arrRight[j];
                    increasement++;
                }
            }
            return arr;
        }
    }
  • 相关阅读:
    统计单词数 OpenJ_Bailian
    整数划分 NBUT
    高精度(x ,/, +, -, %)良心模板
    binary-tree-maximum-path-sum
    2080 特殊的质数肋骨 USACO (深度优先搜索)
    1413 权势二进制
    POJ 1258
    poj 3126
    hdu 1195
    POJ 3752
  • 原文地址:https://www.cnblogs.com/tracer-dhy/p/7474903.html
Copyright © 2020-2023  润新知