-
Notifications
You must be signed in to change notification settings - Fork 42
/
merge_sort.java
58 lines (46 loc) · 1.46 KB
/
merge_sort.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class MergeSort {
public static void mergeSort(int[] arr) {
if (arr.length <= 1) {
return; // Already sorted
}
// Split the array into two halves
int middle = arr.length / 2;
int[] left = new int[middle];
int[] right = new int[arr.length - middle];
System.arraycopy(arr, 0, left, 0, middle);
System.arraycopy(arr, middle, right, 0, arr.length - middle);
// Recursively sort both halves
mergeSort(left);
mergeSort(right);
// Merge the sorted halves
merge(arr, left, right);
}
public static void merge(int[] arr, int[] left, int[] right) {
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++];
}
}
while (i < left.length) {
arr[k++] = left[i++];
}
while (j < right.length) {
arr[k++] = right[j++];
}
}
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
System.out.println("Original Array:");
for (int value : arr) {
System.out.print(value + " ");
}
mergeSort(arr);
System.out.println("\nSorted Array:");
for (int value : arr) {
System.out.print(value + " ");
}
}
}