-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
58 lines (52 loc) · 1.56 KB
/
MergeSort.java
File metadata and controls
58 lines (52 loc) · 1.56 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
//works by dividing an array into smaller subarrays,
// sorting each subarray, and then merging the sorted subarrays back together to form the final sorted array.
//Time Complexity: O(N log(N))
public class MergeSort implements SortingAlgorithm {
public int[] sorty(int[] input) {
mergeSort(input, 0, input.length - 1);
return input;
}
private void mergeSort(int[] input, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
mergeSort(input, low, mid);
mergeSort(input, mid + 1, high);
merge(input, low, mid, high);
}
}
private void merge(int[] input, int low, int mid, int high) {
int leftSize = mid - low + 1;
int rightSize = high - mid;
int[] left = new int[leftSize];
int[] right = new int[rightSize];
for (int i = 0; i < leftSize; i++) {
left[i] = input[low + i];
}
for (int j = 0; j < rightSize; j++) {
right[j] = input[mid + 1 + j];
}
int i = 0;
int j = 0;
int k = low;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
input[k] = left[i];
i++;
} else {
input[k] = right[j];
j++;
}
k++;
}
while (i < leftSize) {
input[k] = left[i];
i++;
k++;
}
while (j < rightSize) {
input[k] = right[j];
j++;
k++;
}
}
}