Created
September 26, 2013 09:13
-
-
Save hantuzun/6711760 to your computer and use it in GitHub Desktop.
MergeSort in Java
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.Arrays; | |
public class MergeSort { | |
public static int[] sort(int[] input) { | |
int len = input.length; | |
int mid = (len) / 2; | |
if (len <=1) | |
return input; | |
return merge(sort(Arrays.copyOfRange(input, 0, mid)), sort(Arrays.copyOfRange(input, mid, len))); | |
} | |
public static int[] merge(int[] a, int[] b) { | |
int[] merged = new int[a.length + b.length]; | |
int i = 0 | |
int j = 0; | |
while (i+j < merged.length) { | |
if (i == a.length) | |
merged[i+j] = b[j]; | |
else if (j == b.length) | |
merged[i+j] = a[i]; | |
else | |
merged[i+j] = (a[i] < b[j]) ? a[i] : b[j]; | |
if (i < a.length && j < b.length) | |
if (merged[i+j] == a[i]) | |
i++; | |
else | |
j++; | |
else | |
if (i == a.length) | |
j++; | |
else | |
i++; | |
} | |
return merged; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment