|
| 1 | +package algs.princeton; |
| 2 | + |
| 3 | + |
| 4 | +public class MergeSort { |
| 5 | + |
| 6 | + int[] Arr; |
| 7 | + int countMerge; |
| 8 | + //constructor |
| 9 | + MergeSort(int[] A){ |
| 10 | + this.Arr=A; |
| 11 | + this.countMerge=0; |
| 12 | + } |
| 13 | + |
| 14 | + public void divide(int[] A, int low, int high){ |
| 15 | + if(low==high) return; |
| 16 | + else{ |
| 17 | + this.countMerge++; |
| 18 | + int mid=(low+high)/2; |
| 19 | + divide(A, low, mid); |
| 20 | + divide(A, mid+1, high); |
| 21 | + mergeAndSort(A, low, mid, high); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + private static void mergeAndSort(int A[], int low, int mid, int high){ |
| 26 | + int m=mid-low+1;//num of elements in the first half of Array A |
| 27 | + int n=high-(mid+1)+1; //num of elements in the second half of Array A |
| 28 | + int[] firstHalf=new int [m]; |
| 29 | + int[] secondHalf=new int [n]; |
| 30 | + |
| 31 | + //extract the first half of already sorted sub array |
| 32 | + for (int i=0; i<m;i++){ |
| 33 | + firstHalf[i]=A[low+i]; |
| 34 | + } |
| 35 | + //extract the second half of already sorted sub array |
| 36 | + for (int j=0; j<n;j++){ |
| 37 | + secondHalf[j]=A[mid+1+j]; |
| 38 | + } |
| 39 | + //sort and merge the two halves together |
| 40 | + int i=0; int j=0; |
| 41 | + while(i<m || j<n){ |
| 42 | + if(i>=m){ |
| 43 | + A[low++]=secondHalf[j++]; |
| 44 | + continue; |
| 45 | + } |
| 46 | + if(j>=n){ |
| 47 | + A[low++]=firstHalf[i++]; |
| 48 | + continue; |
| 49 | + } |
| 50 | + if(firstHalf[i]<secondHalf[j]){ |
| 51 | + A[low++]=firstHalf[i++]; |
| 52 | + }else{ |
| 53 | + A[low++]=secondHalf[j++]; |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public void outputArray(int A[]){ |
| 59 | + for (int i=0;i<A.length;i++){ |
| 60 | + System.out.print(A[i]+", "); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + public void outputMergeCounts(){ |
| 65 | + System.out.println(" "); |
| 66 | + System.out.println("num of merge executions: "+this.countMerge); |
| 67 | + } |
| 68 | + |
| 69 | + public static void main(String[] args) { |
| 70 | + // TODO Auto-generated method stub |
| 71 | + int[] Array={0,1,3,5,7,9,15,13,11,2,4,6,8,10,14,12}; |
| 72 | + MergeSort sort=new MergeSort(Array); |
| 73 | + sort.divide(sort.Arr, 0, sort.Arr.length-1); |
| 74 | + sort.outputArray(sort.Arr); |
| 75 | + sort.outputMergeCounts(); |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments