public class MergeSort { public static void main(String[] args) { int[] input; int length; String inputString = "4143675351981074"; length = inputString.length(); input = new int[length]; for (int i = 0; i < length; i++) { input[i] = Character.getNumericValue(inputString.charAt(i)); } System.out.println("Unsorted list:"); printList(input); System.out.println(); input = sort(input); System.out.println("Sorted list:"); printList(input); } public static int[] sort(int[] initial) { int size = initial.length; if (size == 1) { return initial; } int[] first = new int[size / 2]; int[] second = new int[size - (size / 2)]; System.out.println("Split:"); for (int i = 0; i < first.length; i++) { first[i] = initial[i]; System.out.print(initial[i] + " "); } System.out.println(); for (int j = 0; j < second.length; j++) { second[j] = initial[j + (size / 2)]; System.out.print(initial[j + (size / 2)] + " "); } System.out.println(); System.out.println(); return merge(sort(first), sort(second)); } public static int[] merge(int[] first, int[] second) { System.out.println("Merging:"); for (int a = 0; a < first.length; a++) { System.out.print(first[a] + " "); } System.out.print("and "); for (int b = 0; b < second.length; b++) { System.out.print(second[b] + " "); } System.out.println(); System.out.println(); int[] merged = new int[first.length + second.length]; int pointer1 = 0; int pointer2 = 0; for (int i = 0; i < merged.length; i++) { if (pointer1 == first.length) { merged[i] = second[pointer2]; pointer2++; } else if (pointer2 == second.length) { merged[i] = first[pointer1]; pointer1++; } else if (first[pointer1] < second[pointer2]) { merged[i] = first[pointer1]; pointer1++; } else { merged[i] = second[pointer2]; pointer2++; } } System.out.println("Merged:"); for (int j = 0; j < merged.length; j++) { System.out.print(merged[j] + " "); } System.out.println(); System.out.println(); return merged; } public static void printList(int[] input) { for (int i = 0; i < input.length; i++) { System.out.print(input[i] + " "); } System.out.println(); } }