Created
May 31, 2013 12:19
-
-
Save arunma/5684624 to your computer and use it in GitHub Desktop.
Merge Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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