-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
58 lines (56 loc) · 1.86 KB
/
MergeSort.java
File metadata and controls
58 lines (56 loc) · 1.86 KB
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
package sort;
/**
* Contains implementations for the Merge Sort algorithm.
*/
public class MergeSort {
/**
* Recursive Merge Sort algorithm implementation.
* Efficiency: O(n log n), not in-place.
* @param arr array of elements to be sorted.
* @param left left bound index.
* @param right right bound index.
*/
public void mergeSortRecursive(int[] arr, int left, int right) {
if(right <= left) {
return;
}
int mid = (left + right) / 2;
mergeSortRecursive(arr, left, mid); // recurse left partition
mergeSortRecursive(arr, mid + 1, right); // recurse right partition
merge(arr, left, right, mid); // sort disassembled partitions
}
/**
* Helper method used within the Merge Sort algorithm.
* @param arr the array to be merged into.
* @param left left bound index.
* @param right right bound index.
* @param mid midpoint between left and right index partitions.
*/
public void merge(int[] arr, int left, int right, int mid) {
int leftCount = (mid + 1) - left;
int rightCount = right - mid;
int[] leftArr = new int[leftCount];
int[] rightArr = new int[rightCount];
for(int i = 0; i < leftCount; i++) {
leftArr[i] = arr[left + i];
}
for(int i = 0; i < rightCount; i++) {
rightArr[i] = arr[mid + 1 + i];
}
int l = 0, r = 0, iter = left;
while(l < leftArr.length && r < rightArr.length) {
if(leftArr[l] < rightArr[r]) {
arr[iter++] = leftArr[l++];
}
else {
arr[iter++] = rightArr[r++];
}
}
while(l < leftArr.length) {
arr[iter++] = leftArr[l++];
}
while(r < rightArr.length) {
arr[iter++] = rightArr[r++];
}
}
}