Skip to content

Instantly share code, notes, and snippets.

@ekumachidi
Created October 2, 2015 19:50
Show Gist options
  • Save ekumachidi/c37847ab28848ba7388b to your computer and use it in GitHub Desktop.
Save ekumachidi/c37847ab28848ba7388b to your computer and use it in GitHub Desktop.
Merge Sort Implementation in Java
public class MergeSort {
public static void merge(int[]a,int[] aux, int f, int m, int l) {
for (int k = f; k <= l; k++) {
aux[k] = a[k];
}
int i = f, j = m+1;
for (int k = f; k <= l; k++) {
if(i>m) a[k]=aux[j++];
else if (j>l) a[k]=aux[i++];
else if(aux[j] > aux[i]) a[k]=aux[j++];
else a[k]=aux[i++];
}
}
public static void sort(int[]a,int[] aux, int f, int l) {
if (l<=f) return;
int m = f + (l-f)/2;
sort(a, aux, f, m);
sort(a, aux, m+1, l);
merge(a, aux, f, m, l);
}
public static int[] sort(int[]a) {
int[] aux = new int[a.length];
sort(a, aux, 0, a.length-1);
return a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment