Created
January 20, 2016 08:18
-
-
Save gnarula/b0e6e27ca027d0a5740a to your computer and use it in GitHub Desktop.
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
import java.util.*; | |
public class MergeSort { | |
public static void sort(Comparable[] arr) { | |
Comparable[] temp = new Comparable[arr.length]; | |
sort(arr, temp, 0, arr.length - 1); | |
} | |
public static void sort(Comparable[] arr, Comparable[] aux, int lo, int hi) { | |
if(lo >= hi) { | |
return; | |
} | |
int mid = lo + (hi - lo) / 2; | |
sort(arr, aux, lo, mid); | |
sort(arr, aux, mid + 1, hi); | |
merge(arr, aux, lo, mid, hi); | |
} | |
public static void merge(Comparable[] arr, Comparable[] aux, int lo, int mid, int hi) { | |
for(int i = 0; i <= hi; i++) { | |
aux[i] = arr[i]; | |
} | |
int i = lo; | |
int j = mid + 1; | |
for(int k = lo; k <= hi; k++) { | |
if(i > mid) { | |
arr[k] = aux[j++]; | |
} | |
else if(j > hi) { | |
arr[k] = aux[i++]; | |
} | |
else if(aux[i].compareTo(aux[j]) < 0) { | |
arr[k] = aux[i++]; | |
} | |
else { | |
arr[k] = aux[j++]; | |
} | |
} | |
//System.out.println(Arrays.toString(arr)); | |
} | |
public static void main(String[] args) { | |
//Integer[] arr = {3, 27, 1, 42, 8, 7, 2, 5}; | |
Integer[] arr = {234,51,3,1,2,423,13,4}; | |
sort(arr); | |
System.out.println(Arrays.toString(arr)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment