import java.util.*; public class MergeSort { public static void merge(int[] a, int low, int mid, int high) { System.out.printf("low=%d,mid=%d,high=%d/n",low, mid, high); int left_size = mid-low+1; int[] left = new int[left_size]; for(int i=0; i<left_size; i++) { left[i]=a[low+i]; } int right_size = high-mid; int[] right = new int[right_size]; for(int i=0; i<right_size; i++) { right[i]=a[mid+1+i]; } int size = high-low+1; int i=0, p=0, q=0; for(i=0; i<size && p<left.length && q<right.length; i++) { if(left[p]>right[q]) { a[i+low]=right[q++]; } else { a[i+low]=left[p++]; } } while(p<left.length) { a[i+low]=left[p]; i++; p++; } while(q<right.length) { a[i+low]=right[q]; i++; q++; } } public static void mergeWithSentinels(int[] a, int low, int mid, int high) { System.out.printf("low=%d,mid=%d,high=%d/n",low, mid, high); int left_size = mid-low+2; int[] left = new int[left_size]; for(int i=0; i<left_size-1; i++) { left[i]=a[low+i]; } left[left_size-1]=Integer.MAX_VALUE; int right_size = high-mid+1; int[] right = new int[right_size]; for(int i=0; i<right_size-1; i++) { right[i]=a[mid+1+i]; } right[right_size-1]=Integer.MAX_VALUE; int size = high-low+1; int p=0, q=0; for(int i=0; i<size; i++) { if(left[p]>right[q]) { a[i+low]=right[q++]; } else { a[i+low]=left[p++]; } } } public static void mergeSort(int[] a, int low, int high) { if(low==high) { return; } int mid = low + (high-low)/2; mergeSort(a, low, mid); mergeSort(a, mid+1, high); merge1(a, low, mid, high); } public static void main(String[] args) { int[] a = {5,2,4,7,1,3,2,6}; System.out.println("Origin: " + Arrays.toString(a)); mergeSort(a, 0, a.length-1); System.out.println("Sorted: " + Arrays.toString(a)); } }