Created
September 11, 2016 13:06
-
-
Save nichtemna/567b325d17fee52ec6b56534048aae60 to your computer and use it in GitHub Desktop.
Merge sort
This file contains hidden or 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
| /** | |
| * | |
| Merge sort O(n log(n)): | |
| - Break array in two parts and sort them recursively | |
| - Merge two sorted array in one resulting array | |
| */ | |
| public class MergeSort { | |
| public static void main(String[] args) { | |
| Scanner scanner = new Scanner(System.in); | |
| int n = scanner.nextInt(); | |
| int[] array = new int[n]; | |
| for (int i = 0; i < n; i++) { | |
| array[i] = scanner.nextInt(); | |
| } | |
| array = getArraySorted(array, 0, array.length - 1); | |
| for (int i : array) { | |
| System.out.print(i + " "); | |
| } | |
| } | |
| private static int[] getArraySorted(int[] array, int start, int end) { | |
| int[] res = new int[end + 1 - start]; | |
| int j = 0; | |
| for (int i = start; i <= end; i++) { | |
| res[j] = array[i]; | |
| j++; | |
| } | |
| start = 0; | |
| end = res.length - 1; | |
| if (start == end) { | |
| return res; | |
| } | |
| int mid = (start + end) / 2; | |
| int[] sortedLeft = getArraySorted(res, start, mid); | |
| int[] sortedRight = getArraySorted(res, mid + 1, end); | |
| array = merge(res, sortedLeft, sortedRight, start, end); | |
| return array; | |
| } | |
| private static int[] merge(int[] array, int[] sortedLeft, int[] sortedRight, int start, int end) { | |
| int leftIndex = 0; | |
| int rightIndex = 0; | |
| for (int i = start; i <= end; i++) { | |
| if (leftIndex < sortedLeft.length && rightIndex < sortedRight.length) { | |
| if (sortedLeft[leftIndex] < sortedRight[rightIndex]) { | |
| array[i] = sortedLeft[leftIndex]; | |
| leftIndex++; | |
| } else { | |
| array[i] = sortedRight[rightIndex]; | |
| rightIndex++; | |
| } | |
| } else if (leftIndex < sortedLeft.length) { | |
| array[i] = sortedLeft[leftIndex]; | |
| leftIndex++; | |
| } else if (rightIndex < sortedRight.length) { | |
| array[i] = sortedRight[rightIndex]; | |
| rightIndex++; | |
| } | |
| } | |
| return array; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment