Merge Sort
Merge sort is a divide-and-conquer algorithm that works by breaking down the original problem into smaller subproblems, recursively solving them, and then combining them to produce the final sorted output.
The basic idea behind merge sort is to divide the unsorted list into (n) sublists, each containing one element, and repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This final sublist will be the sorted list.
Let's take a closer look at the implementation in Java:
TEXT/X-JAVA
1public class MergeSort {
2
3 public static void mergeSort(int[] arr) {
4 if (arr.length < 2) return;
5 int mid = arr.length / 2;
6 int[] left = new int[mid];
7 int[] right = new int[arr.length - mid];
8
9 // Copy elements from the original array to the left and right subarrays
10 for (int i = 0; i < mid; i++) {
11 left[i] = arr[i];
12 }
13 for (int i = mid; i < arr.length; i++) {
14 right[i - mid] = arr[i];
15 }
16
17 // Recursively sort the left and right subarrays
18 mergeSort(left);
19 mergeSort(right);
20
21 // Merge the sorted subarrays
22 merge(left, right, arr);
23 }
24
25 public static void merge(int[] left, int[] right, int[] arr) {
26 int i = 0, j = 0, k = 0;
27
28 // Merge the two subarrays in sorted order
29 while (i < left.length && j < right.length) {
30 if (left[i] <= right[j]) {
31 arr[k++] = left[i++];
32 } else {
33 arr[k++] = right[j++];
34 }
35 }
36
37 // Copy any remaining elements from the left subarray
38 while (i < left.length) {
39 arr[k++] = left[i++];
40 }
41
42 // Copy any remaining elements from the right subarray
43 while (j < right.length) {
44 arr[k++] = right[j++];
45 }
46 }
47
48 public static void main(String[] args) {
49 int[] arr = {5, 2, 7, 1, 3, 6, 4};
50 mergeSort(arr);
51 for (int num : arr) {
52 System.out.print(num + " ");
53 }
54 }
55
56}
xxxxxxxxxx
46
}
public class MergeSort {
public static void mergeSort(int[] arr) {
if (arr.length < 2) return;
int mid = arr.length / 2;
int[] left = new int[mid];
int[] right = new int[arr.length - mid];
for (int i = 0; i < mid; i++) {
left[i] = arr[i];
}
for (int i = mid; i < arr.length; i++) {
right[i - mid] = arr[i];
}
mergeSort(left);
mergeSort(right);
merge(left, right, arr);
}
public static void merge(int[] left, int[] right, int[] arr) {
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment