1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public static void main(String[] args) { int arr[] ={9,8,7,4,6,3,5,0}; System.out.println(Arrays.toString(MergeSort(arr,0,7))); }
public static int[] MergeSort(int arr[] , int start ,int end){
if(start>=end){ return arr; } int mid=(start+end)/2; MergeSort(arr,start,mid); MergeSort(arr,mid+1,end); twoMerge(arr,start,mid,end); return arr;
}
public static int[] twoMerge(int arr[],int left,int mid,int right ){ int[] temp =new int[right-left+1]; int i=left; int j=mid+1; int index=0; while(i<=mid&&j<=right){ if(arr[i]<arr[j]){ temp[index]=arr[i]; i++; index++; }else{ temp[index]=arr[j]; j++; index++; } }
while(i<=mid){ temp[index]=arr[i]; i++; index++; } while(j<=right){ temp[index]=arr[j]; j++; index++; }
int start=left; for(int k=0;k<temp.length;k++){ arr[start+k]=temp[k]; } return temp; }
|