|
| 1 | +import java.util.Arrays; |
| 2 | + |
| 3 | +public class MergeSort { |
| 4 | + public static void main(String[] args) { |
| 5 | + int[] arr = {-1,2,6,5,4,7,8,9,11,0}; |
| 6 | + System.out.println(Arrays.toString(sort(arr))); |
| 7 | + sortinplace(arr,0, arr.length); |
| 8 | + System.out.println(Arrays.toString(arr)); |
| 9 | + |
| 10 | + } |
| 11 | + |
| 12 | + private static void sortinplace(int[] arr,int s , int e) { |
| 13 | + if(e-s==1) |
| 14 | + return; |
| 15 | + int mid = (e + s)/2; |
| 16 | + sortinplace(arr,s,mid); |
| 17 | + sortinplace(arr,mid,e); |
| 18 | + mergeplace(arr,s,mid,e); |
| 19 | + } |
| 20 | + private static void mergeplace(int[] arr , int s, int m , int e){ |
| 21 | + int[] mix = new int[e-s]; |
| 22 | + int i = s; |
| 23 | + int j = m; |
| 24 | + int k = 0; |
| 25 | + while(i<m && j<e){ |
| 26 | + if(arr[i]>arr[j]) { |
| 27 | + mix[k] = arr[j]; |
| 28 | + j++; |
| 29 | + } |
| 30 | + else { |
| 31 | + mix[k] = arr[i]; |
| 32 | + i++; |
| 33 | + } |
| 34 | + k++; |
| 35 | + } |
| 36 | + while(i<m){ |
| 37 | + mix[k]=arr[i]; |
| 38 | + i++; |
| 39 | + k++; |
| 40 | + } |
| 41 | + while(j<e){ |
| 42 | + mix[k]=arr[j]; |
| 43 | + j++; |
| 44 | + k++; |
| 45 | + } |
| 46 | + |
| 47 | + for(i = 0 ; i < mix.length ; i++){ |
| 48 | + arr[s+i]=mix[i]; |
| 49 | + } |
| 50 | + |
| 51 | + } |
| 52 | + |
| 53 | + private static int[] sort(int[] arr) { |
| 54 | + if(arr.length==1) |
| 55 | + return arr; |
| 56 | + int mid = arr.length/2; |
| 57 | + int[] left = sort(Arrays.copyOfRange(arr,0,mid)); |
| 58 | + int[] right = sort(Arrays.copyOfRange(arr,mid,arr.length)); |
| 59 | + return merge(left, right); |
| 60 | + } |
| 61 | + |
| 62 | + private static int[] merge(int[] first, int[] second) { |
| 63 | + int[] mix = new int[first.length+second.length]; |
| 64 | + int i=0,j=0,k=0; |
| 65 | + while(i<first.length && j<second.length){ |
| 66 | + if(first[i]<second[j]) { |
| 67 | + mix[k] = first[i]; |
| 68 | + i++; |
| 69 | + } |
| 70 | + else{ |
| 71 | + mix[k]=second[j]; |
| 72 | + j++; |
| 73 | + } |
| 74 | + k++; |
| 75 | + } |
| 76 | + while(i<first.length){ |
| 77 | + mix[k]=first[i]; |
| 78 | + i++; |
| 79 | + k++; |
| 80 | + } |
| 81 | + while(j<second.length){ |
| 82 | + mix[k]=second[j]; |
| 83 | + j++; |
| 84 | + k++; |
| 85 | + } |
| 86 | + return mix; |
| 87 | + } |
| 88 | +} |
0 commit comments