-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15. Merge Sort.js
More file actions
39 lines (36 loc) · 961 Bytes
/
15. Merge Sort.js
File metadata and controls
39 lines (36 loc) · 961 Bytes
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
// MERGE SORT
// É uma combinação de spliting, merging e sorting. Decompõe o array em mini-arrays de 1 elemento, depois faz o caminho da volta reordenando.
// Complexidade:
// Time: O(n log n) for all cases
// Space: O(n)
function merge(arr1, arr2) {
let results = [];
let i = 0;
let j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr2[j] > arr1[i]) {
results.push(arr1[i]);
i++;
} else {
results.push(arr2[j])
j++;
}
}
while (i < arr1.length) {
results.push(arr1[i])
i++;
}
while (j < arr2.length) {
results.push(arr2[j])
j++;
}
return results;
}
function mergeSort(arr) {
if (arr.length <= 1) return arr;
let mid = Math.floor(arr.length / 2);
let left = mergeSort(arr.slice(0, mid));
let right = mergeSort(arr.slice(mid));
return merge(left, right);
}
mergeSort([10, 24, 76, 73])