二路归并排序
public class BinaMergeSort { // 将数组a[start..mid],a[mid+1..end]合并到数组union static void Merge(int[] a, int start, int mid, int end, int[] union) { // 左边数组起始下标 int left = start; // 右边数组起始下标 int right = mid + 1; // 合并到union的起始下标 int uPos = start; for (; left <= mid && right <= end;) { if (a[left] > a[right]) { union[uPos++] = a[right++]; } else { union[uPos++] = a[left++]; } } while (left <= mid) { union[uPos++] = a[left++]; } while (right <= end) { union[uPos++] = a[right++]; } //合并好后再将其赋给a for(int i=start;i<=end;i++){ a[i] = union[i]; } } static void MergeSort(int a[], int low, int high, int[] union) { if (low < high) { int mid = (low + high) / 2; MergeSort(a, low, mid, union); MergeSort(a, mid + 1, high, union); Merge(a, low, mid, high, union); } } public static void main(String[] args){ int[] a = { 5, 3, 2, 0, 8, 4, 6, 7, 1, 4 }; //union为辅助数组 int[] union = new int[a.length]; MergeSort(a, 0, a.length - 1, union); for (int i : a) { System.out.print(i + " "); } } }