采用分治思想,分治其实也是一种递归,递归的三个条件:递推公式,终止条件,递归代码实现
package dsaa.归并排序; import java.util.Arrays; /* * 归并排序 * */ public class MergeSortSolution { public static int[] mergeSort(int[] a, int size) { if (size <= 1) return a; return mergeSortSolution(a); } private static int[] mergeSortSolution(int[] a) { /* 终止条件 */ if (a.length <= 1) return a; /* 每次递归调用中间位置作为子序列的分割点 */ int mid = a.length / 2; /* 分治递归 */ int[] leftArray = mergeSortSolution(Arrays.copyOfRange(a, 0, mid)); int[] rightArray = mergeSortSolution(Arrays.copyOfRange(a, mid, a.length)); int[] temp = merge(a, leftArray, rightArray); return temp; } private static int[] merge(int[] a, int[] leftArray, int[] rightArray) { int[] temp = new int[a.length]; int i = 0; int j = 0; int k = 0; while (k < temp.length) { while (i < leftArray.length && j < rightArray.length) { if (leftArray[i] < rightArray[j]) { temp[k] = leftArray[i]; ++k; ++i; } else { temp[k] = rightArray[j]; ++k; ++j; } if (i >= leftArray.length) { for (int l = j; l < rightArray.length; ++l) { temp[k] = rightArray[l]; ++k; } } if (j >= rightArray.length) { for (int m = i; m < leftArray.length; ++m) { temp[k] = leftArray[m]; ++k; } } } } return temp; } public static void main(String[] args) { int[] a = { 4, 3, 5, 6, 1, 7, 2 }; int size = a.length; int[] result = MergeSortSolution.mergeSort(a, size); for (int i = 0; i < result.length; ++i) { System.out.print(result[i] + " "); } } }