import java.util.*;
public class MergeSort {
public int[] mergeSort(int[] arr) {
if(arr==null||arr.length==0)
return arr;
sort(arr,0,arr.length-1);
return arr;
}
private void sort(int []arr,int left,int right){
if(left<right){
int middle = (left+right)/2;
sort(arr,left,middle);
sort(arr,middle+1,right);
merge(arr,left,middle,right);
}
}
private void merge(int []arr,int left,int middle,int right){
int [] tempArr = new int[right-left+1];
int l = left;
int m = middle+1;
int index = 0;
while(l<=middle&&m<=right){
if(arr[l]<arr[m]){
tempArr[index++]=arr[l++];
}else{
tempArr[index++]=arr[m++];
}
}
while(l<=middle){
tempArr[index++] = arr[l++];
}
while(m<=right){
tempArr[index++] = arr[m++];
}
for(int i=0;i<tempArr.length;i++){
arr[left+i] = tempArr[i];
}
}
}