Created
March 2, 2016 05:32
-
-
Save connlark/320d358b808ede5853e0 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.Arrays; | |
/** | |
* Created by Connor on 3/1/16. | |
*/ | |
public class MergeSort { | |
static int lc,rc;//static counters | |
public static int[] mergeSort(int[] arr){ | |
if (arr.length <= 1) return arr; //base case | |
else { | |
int middleRight = (int)Math.ceil(arr.length/2.0); | |
int[] left,right; //cutting array in half (if array is an odd # -> left half gets extra #) | |
left = Arrays.copyOf(arr,middleRight); | |
right = Arrays.copyOfRange(arr,middleRight,arr.length); | |
left = mergeSort(left); //the recursive call returns the left half of original data sorted | |
right = mergeSort(right); //the recursive call returns the right half of original data sorted | |
return merge(left,right); //merges the two sorted halves | |
} | |
} | |
private static int[] merge(int[] leftSide, int[] rightSide){ | |
int[] result = new int[leftSide.length + rightSide.length]; | |
lc = 0; rc = 0; //sets the counters of each array (static ints) to 0 | |
for (int i = 0; i < result.length; i++) { | |
if (lc != leftSide.length && (rc == rightSide.length || rightSide[rc] > leftSide[lc])){ | |
result[i] = leftSide[lc++]; | |
} | |
else result[i] = rightSide[rc++]; | |
} | |
return result; | |
} | |
public static void printArray(int[] a){ | |
for (int n:a) { | |
System.out.print("[" + n + "] "); | |
} | |
System.out.println(); | |
} | |
public static int[] arrayGenerator(int size, int min, int max){ | |
int[] result = new int[size]; | |
for (int i = 0; i < size; i++) { | |
result[i] = min + (int)(Math.random() * ((max - min) + 1)); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment