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; } }