Skip to content

Commit 4fda30e

Browse files
committed
Created Java Merge Sort Implementation
1 parent ab49890 commit 4fda30e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Sorting/MergeSort.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
public class MergeSort {
2+
3+
public static void mergeSort(int[] arr) {
4+
mergeSort(arr, 0, arr.length-1);
5+
}
6+
7+
public static void mergeSort(int[] arr, int leftIndex, int rightIndex) {
8+
int arrLen = rightIndex + 1 - leftIndex;
9+
10+
if (arrLen > 1) {
11+
int midIndex = (leftIndex + rightIndex) / 2;
12+
13+
mergeSort(arr, leftIndex, midIndex);
14+
mergeSort(arr, midIndex+1, rightIndex);
15+
merge(arr, leftIndex, midIndex, rightIndex);
16+
}
17+
}
18+
19+
public static void merge(int[] arr, int leftIndex, int midIndex, int rightIndex) {
20+
int leftLen = midIndex + 1 - leftIndex;
21+
int rightLen = rightIndex - midIndex;
22+
23+
int[] leftArr = new int[leftLen];
24+
int[] rightArr = new int[rightLen];
25+
26+
for (int i = 0; i < leftLen; i++) {
27+
leftArr[i] = arr[i+leftIndex];
28+
}
29+
30+
for (int j = 0; j < rightLen; j++) {
31+
rightArr[j] = arr[j+midIndex+1];
32+
}
33+
34+
int i = 0;
35+
int j = 0;
36+
int k = leftIndex;
37+
38+
while (i < leftLen && j < rightLen) {
39+
if (leftArr[i] < rightArr[j]) {
40+
arr[k] = leftArr[i];
41+
i++;
42+
} else {
43+
arr[k] = rightArr[j];
44+
j++;
45+
}
46+
k++;
47+
}
48+
49+
while (i < leftLen) {
50+
arr[k] = leftArr[i];
51+
i++;
52+
k++;
53+
}
54+
55+
while (j < rightLen) {
56+
arr[k] = rightArr[j];
57+
j++;
58+
k++;
59+
}
60+
}
61+
}

0 commit comments

Comments
 (0)