Merge Sort Java Implementation
import java.util.Arrays; public class MergeSort { public static void sort(int[] inputArray) { sort(inputArray, 0, inputArray.length-1); } public static void sort(int[] inputArray, int start, int end) { if(end <=start) { return; // array travels seems done } int mid = (start + end) / 2; sort(inputArray, start, mid); sort(inputArray, mid+1,end); merge(inputArray, start, mid, end); } public static void merge(int[] inputArray, int start, int mid, int end) { int tempArray[] = new int[end - start+1]; int leftCounter = start; int rightCounter = mid+1; int tempArrayCounter=0; while(leftCounter <=mid && rightCounter<=end) { if(inputArray[leftCounter] < inputArray[rightCounter]) { tempArray[tempArrayCounter]=inputArray[leftCounter]; leftCounter++; }else { tempArray[tempArrayCounter]=inputArray[rightCounter]; rightCounter++; } tempArrayCounter++; } // left and right should have been sorted by now if(leftCounter <= mid) { while(leftCounter <= mid) { tempArray[tempArrayCounter] = inputArray[leftCounter]; leftCounter++; tempArrayCounter++; } } else if(rightCounter <= end) { while(rightCounter <= end) { tempArray[tempArrayCounter]= inputArray[rightCounter]; rightCounter++; tempArrayCounter++; } } // copy temp array to input array for(int i =0;i<tempArray.length;i++) { inputArray[start+i] = tempArray[i]; } } public static void main(String[] args) { int[] inputArray = {9,7,3,10,1,8,4,6}; sort(inputArray); System.out.println(Arrays.toString(inputArray)); } }
Output:
[1, 3, 4, 6, 7, 8, 9, 10]
startup talky There is definately a lot to find out about this subject. I like all the points you made
Real Estate I am truly thankful to the owner of this web site who has shared this fantastic piece of writing at at this place.
Baddiehubs Awesome! Its genuinely remarkable post, I have got much clear idea regarding from this post . Baddiehubs
BYU Cougars For the reason that the admin of this site is working, no uncertainty very quickly it will be renowned, due to its quality contents.
Aroma Sensei I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
Tech Learner This was beautiful Admin. Thank you for your reflections.
Isla Moon Nice post. I learn something totally new and challenging on websites
Clochant Good post! We will be linking to this particularly great post on our site. Keep up the great writing
Glue Dream strain This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!
Serving Iraq with pride, BWER supplies high-performance weighbridges designed to improve transport logistics, reduce inaccuracies, and optimize industrial processes across all sectors.
NY weekly Pretty! This has been a really wonderful post. Many thanks for providing these details.