bangash110-avatar

Implement the Merge Sort algorithm in JAVA?

I want the java program(source code).
0%

6 replies

over 5 years ago
erickson-balanga-avatar
MergeSort Algorithm In Java
  1. set left = 0, right = N-1.
  2. compute middle = (left + right)/2.
  3. Call subroutine merge_sort (myArray,left,middle) => this sorts first half of the array.
  4. Call subroutine merge_sort (myArray,middle+1,right) => this will sort the second half of the array.
100%
over 5 years ago
bhumika-shah-avatar
The Merge Sort algorithm combines the split and merge step, to give us a sorted array.
  • First, we keep splitting the array recursively, till we get all subarrays of size 1. Recall how we practiced this in the Split step
  • Then, once the array cannot be split further, we start tracing back on our Merge Sort tree
  • As we trace back, we keep merging the child subarrays and overwriting the parent subarrays by their sorted forms.
Merge sort usually is considered a two step process, first divide it into two halves and then implement sorting.All these polymorphic algorithms are pieces of reusable functionality provided by the Java platform. All of them come from the Collections class, and all take the form of static methods whose first argument is the collection on which the operation is to be performed. ​ You can find a good tutorial of Java collections on https://docs.oracle.com/javase/tutorial/collections/algorithms/index.html#sorting ​ And for your program : MergeSort.java ​ //MergeSort ​ class Sorting { ​ public static void merge(int[] left_arr,int[] right_arr, int[] arr,int left_size, int right_size){ int i=0,l=0,r = 0; //The while loops check the conditions for merging while(l<left\_size && r<right\_size){ if(left\_arr[l]<right\_arr[r]){ arr[i++] = left\_arr[l++]; } else{ arr[i++] = right\_arr[r++]; } } while(l<left\_size){ arr[i++] = left\_arr[l++]; } while(r<right\_size){ arr[i++] = right\_arr[r++]; } } ​ public static void mergeSort(int [] arr, int len){ if (len < 2){return;} int mid = len / 2; int [] left\_arr = new int[mid]; int [] right\_arr = new int[len-mid]; //Dividing array into two and copying into two separate arrays int k = 0; for(int i = 0;i<len;++i){ if(i<mid){ left\_arr[i] = arr[i]; } else{ right\_arr[k] = arr[i]; k = k+1; } } // Recursively calling the function to divide the subarrays further mergeSort(left\_arr,mid); mergeSort(right\_arr,len-mid); // Calling the merge method on each subdivision merge(left\_arr,right\_arr,arr,mid,len-mid); } ​ public static void main( String args[] ) { int [] array = {12,1,10,50,5,15,45}; mergeSort(array,array.length); for(int i =0; i< array.length;++i){ System.out.print(array[i]+ " "); } } } ​