标签:
package leetcode.sort; import java.util.Arrays; import java.util.Random; /** * Created by blank on 2015-09-22 上午11:42. */ public class MergeSort { public static void main(String[] args) { int[] arr = new int[20]; for (int i = 0; i < 20; i++) { arr[i] = new Random().nextInt(100); } mergeSort(arr, 0, 19); System.out.println(Arrays.toString(arr)); } public static void mergeSort(int[] num, int left, int right) { if (num == null || left >= right) { return; } int mid = (left + right) >>> 1; mergeSort(num, left, mid); mergeSort(num, mid + 1, right); merge(num, left, mid, right); } public static void merge(int[] num, int left, int mid, int right) { if (num == null) { return; } int[] copy = num.clone(); int i, j, k = left; for (i = left, j = mid + 1; i <= mid && j <= right; k++) { if (copy[i] < copy[j]) num[k] = copy[i++]; else num[k] = copy[j++]; } while (i <= mid) { num[k++] = copy[i++]; } while (j <= right) { num[k++] = copy[j++]; } } }
标签:
原文地址:http://www.cnblogs.com/aboutblank/p/4828546.html