标签:
/** * Created by icecookstar on 2015/11/3. * 归并排序 */ public class MergeSort { private static void merge(int[] matrix, int first, int middle, int last) { int[] tmp = new int[last - first + 1]; int i = first; int m = middle; int j = middle + 1; int n = last; int k = 0; while (i <= m && j <= n) { if (matrix[i] <= matrix[j]) { tmp[k++] = matrix[i++]; } else { tmp[k++] = matrix[j++]; } } while (i <= m) { tmp[k++] = matrix[i++]; } while (j <= n) { tmp[k++] = matrix[j++]; } for (int l = 0; l < k; l++) { matrix[first + l] = tmp[l]; } } private static void mergeSort(int[] matrix, int i, int j) { if (i < j) { int middle = (i + j) / 2; mergeSort(matrix, i, middle); mergeSort(matrix, middle + 1, j); merge(matrix, i, middle, j); } } public static void main(String[] args) { int[] matrix = new int[]{1, 3, 5, 4, 8, 10, 9, 20, 18, 18, 10}; mergeSort(matrix, 0, matrix.length - 1); for (int i : matrix) { System.out.print(i + " "); } } }
标签:
原文地址:http://www.cnblogs.com/duanxingxing/p/4934609.html