Skip to content

Instantly share code, notes, and snippets.

@arunma
Created May 31, 2013 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunma/5684624 to your computer and use it in GitHub Desktop.
Save arunma/5684624 to your computer and use it in GitHub Desktop.
Merge Sort
package com.sorting.merge;
import static com.sorting.insert.SortUtils.less;
public class MergeSort {
public Comparable[] sort(Comparable[] items) {
sort (items,new Comparable[items.length], 0, items.length-1);
return items;
}
public void sort (Comparable[] input, Comparable[] aux, int lowIndex, int highIndex){
if (highIndex<=lowIndex) return;
int midIndex=lowIndex+(highIndex-lowIndex)/2;
sort (input, aux, lowIndex, midIndex);
sort (input, aux, midIndex+1, highIndex);
merge (input, aux, lowIndex, midIndex, highIndex);
}
public void merge(Comparable[] input, Comparable[] aux, int lowIndex, int midIndex, int highIndex){
if (input==null || aux==null){
throw new IllegalArgumentException("Input or Auxillary array are null");
}
for (int temp=lowIndex;temp<=highIndex;temp++){
aux[temp]=input[temp];
}
int i=lowIndex,j=midIndex+1;
for (int counter=lowIndex;counter<=highIndex;counter++){
if (i>midIndex){
input[counter]=aux[j];
j++;
}
else if (j>highIndex){
input[counter]=aux[i];
i++;
}
else if (less(aux[j], aux[i])){
input[counter]=aux[j];
j++;
}
else{
input[counter]=aux[i];
i++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment