public class MergeSort {
static int[] assist = null;
public static void main(String[] args) {
int[] a = {9,8,7,6,5,4,3,2,1};
sort(a);
System.out.println(Arrays.toString(a));
}
public static void sort(int[] a){
assist = new int[a.length];
sort(a,0,a.length - 1);
}
public static void sort(int[] a, int l, int r){
if(l >= r) return;
int mid = (l + r)/2;
sort(a,l,mid);
sort(a,mid+1,r);
merge(a,l,mid,r);
}
public static void merge(int[] a, int l, int mid, int r){
int i = l;
int p1 = l;
int p2 = mid + 1;
while(p1 <= mid && p2 <= r){
if(a[p1] > a[p2]){
assist[i++] = a[p2++];
}else{
assist[i++] = a[p1++];
}
}
while(p1 <= mid) assist[i++] = a[p1++];
while(p2 <= r) assist[i++] = a[p2++];
for(int index = l; index <= r; index++){
a[index] = assist[index];
}
}
}
private static void process(int[] arr, int left, int right) {
if(left == right){
return;
}
int mid = left + (right - left) / 2;
process(arr, left, mid);
process(arr, mid + 1, right);
merge(arr, left, mid, right);
}
private static void merge(int[] arr, int left, int mid, int right) {
int[] help = new int[right - left + 1];
int i = 0;
int l = left, r = mid + 1;
while(l <= mid && r <= right){
if(arr[l] < arr[r]){
help[i++] = arr[l++];
}else{
help[i++] = arr[r++];
}
}
while(l <= mid){
help[i++] = arr[l++];
}
while(r <= right){
help[i++] = arr[r++];
}
for(i = 0; i < help.length; i++){
arr[left + i] = help[i];
}
}