|
| 1 | +package com.tozu.sorting; |
| 2 | + |
| 3 | +import java.util.Random; |
| 4 | + |
| 5 | +public class MergeSort { |
| 6 | + |
| 7 | + public static void mergeSort(int[] arr) { |
| 8 | + // In this case, the array only contains one element. |
| 9 | + // That means, that it is already sorted. |
| 10 | + if (arr.length <= 1) { |
| 11 | + return; |
| 12 | + } |
| 13 | + |
| 14 | + int mid = arr.length / 2; |
| 15 | + |
| 16 | + int[] left = new int[mid]; |
| 17 | + int[] right = new int[arr.length - mid]; |
| 18 | + |
| 19 | + // Data copying |
| 20 | + System.arraycopy(arr, 0, left, 0, mid); |
| 21 | + System.arraycopy(arr, mid, right, 0, arr.length - mid); |
| 22 | + |
| 23 | + // Recursive sorting |
| 24 | + mergeSort(left); |
| 25 | + mergeSort(right); |
| 26 | + |
| 27 | + // Merge |
| 28 | + merge(arr, left, right); |
| 29 | + } |
| 30 | + |
| 31 | + private static void merge(int[] arr, int[] left, int[] right) { |
| 32 | + int i = 0, j = 0, k = 0; |
| 33 | + |
| 34 | + while (i < left.length && j < right.length) { |
| 35 | + if (left[i] <= right[j]) { |
| 36 | + arr[k++] = left[i++]; |
| 37 | + } else { |
| 38 | + arr[k++] = right[j++]; |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + // Remaining elements |
| 43 | + while (i < left.length) { |
| 44 | + arr[k++] = left[i++]; |
| 45 | + } |
| 46 | + |
| 47 | + while (j < right.length) { |
| 48 | + arr[k++] = right[j++]; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public static void main(String[] args) { |
| 53 | + |
| 54 | + Random random = new Random(); |
| 55 | + |
| 56 | + // Declare an array with X amount of elements |
| 57 | + int[] arr = new int[100000000]; |
| 58 | + |
| 59 | + // Add random elements to the array |
| 60 | + for (int i = 0; i < arr.length; i++) { |
| 61 | + arr[i] = random.nextInt(1000); |
| 62 | + } |
| 63 | + |
| 64 | + mergeSort(arr); |
| 65 | + |
| 66 | + for (int num : arr) { |
| 67 | + System.out.print(num + " "); |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments