public class Sort {
public static void MergeSort(int[] array){
int[] temp = new int[array.length];
MergeSort(array,0,array.length-1,temp);
}
public static void MergeSort(int[] array,int left, int right, int[] temp){
if(left>=right){
return;
}
int mid = (left+right)/2;
MergeSort(array,left,mid,temp);
MergeSort(array,mid+1,right,temp);
Merge(array,left,mid,right,temp);
}
public static void Merge(int[] array,int left,int mid, int right, int[] temp){
int i = 0;
int j = left;
int k = mid+1;
while (j<=mid && k<=right){
if(array[j]<array[k]){
temp[i++] = array[j++];
} else {
temp[i++] = array[k++];
}
}
while (j<=mid){
temp[i++] = array[j++];
}
while (k<=right){
temp[i++] = array[k++];
}
for (int n=0; n<i; n++){
array[left+n]=temp[n];
}
}
public static void main(String[] args) {
int[] array = new int[]{9,8,7,6,5,1,2,3,4};
MergeSort(array);
for (Object obj:array
) {
System.out.println(obj);
}
}
}