Java implement a merge sort class import javautilList impor
Java implement a merge sort class .
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
class MergeSort {
/**
* Sorts the list provided as input
* Does not return anything (as this is an in-place sort)
*/
public static void sort(List<Integer> list) {
//TODO call the private static void sort method.
}
private static void sort(List<Integer> list, int startIndex, int endIndex){
//TODO
}
Solution
import java.util.ArrayList;
public class MergeSort {
public static void sort(ArrayList<Integer> list){
sort(list,0,list.size()-1);
}
private static void sort(ArrayList<Integer> list,int startIndex, int endIndex){
divide(list,startIndex,endIndex);
}
public static void divide(ArrayList<Integer> list,int startIndex,int endIndex){
//Divide till you breakdown your list to single element
if(startIndex<endIndex && (endIndex-startIndex)>=1){
int mid = (endIndex + startIndex)/2;
divide(list,startIndex, mid);
divide(list,mid+1, endIndex);
//merging Sorted array produce above into one sorted array
conqur(list,startIndex,mid,endIndex);
}
}
public static void conqur(ArrayList<Integer> inputArray,int startIndex,int midIndex,int endIndex){
//Below is the mergedarray that will be sorted array Array[i-midIndex] , Array[(midIndex+1)-endIndex]
ArrayList<Integer> mergedSortedArray = new ArrayList<Integer>();
int leftIndex = startIndex;
int rightIndex = midIndex+1;
while(leftIndex<=midIndex && rightIndex<=endIndex){
if(inputArray.get(leftIndex)<=inputArray.get(rightIndex)){
mergedSortedArray.add(inputArray.get(leftIndex));
leftIndex++;
}else{
mergedSortedArray.add(inputArray.get(rightIndex));
rightIndex++;
}
}
//Either of below while loop will execute
while(leftIndex<=midIndex){
mergedSortedArray.add(inputArray.get(leftIndex));
leftIndex++;
}
while(rightIndex<=endIndex){
mergedSortedArray.add(inputArray.get(rightIndex));
rightIndex++;
}
int i = 0;
int j = startIndex;
//Setting sorted array to original one
while(i<mergedSortedArray.size()){
inputArray.set(j, mergedSortedArray.get(i++));
j++;
}
}
}

