Skip to content

Commit 05fbf43

Browse files
jorgegonzalezyangshun
authored andcommitted
Create mergeSort.js (yangshun#38)
1 parent ca10d55 commit 05fbf43

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

utilities/javascript/mergeSort.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
function mergeSort(arr) {
2+
if (arr.length < 2) {
3+
// Arrays of length 0 or 1 are sorted by definition
4+
return arr;
5+
}
6+
7+
const left = arr.slice(0, Math.floor(arr.length / 2));
8+
const right = arr.slice(Math.floor(arr.length / 2), Math.floor(arr.length));
9+
10+
return merge(mergeSort(left), mergeSort(right));
11+
}
12+
13+
function merge(arr1, arr2) {
14+
const merged = [];
15+
16+
let i = 0;
17+
let j = 0;
18+
19+
while (i < arr1.length && j < arr2.length) {
20+
if (arr1[i] < arr2[j]) {
21+
merged.push(arr1[i]);
22+
i++;
23+
} else if (arr2[j] < arr1[i]) {
24+
merged.push(arr2[j]);
25+
j++;
26+
} else {
27+
merged.push(arr1[i]);
28+
i++;
29+
j++;
30+
}
31+
}
32+
33+
while (i < arr1.length) {
34+
merged.push(arr1[i]);
35+
i++;
36+
}
37+
38+
while (j < arr2.length) {
39+
merged.push(arr2[j]);
40+
j++;
41+
}
42+
43+
return merged;
44+
}
45+
46+
const arr1 = [7, 2, 4, 3, 1, 2];
47+
const arr2 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
48+
const arr3 = [98322, 3242, 876, -234, 34, 12331];
49+
const arr4 = [1, 2, 3, 4, 5, 0];
50+
51+
console.log(mergeSort(arr1));
52+
console.log(mergeSort(arr2));
53+
console.log(mergeSort(arr3));
54+
console.log(mergeSort(arr4));

0 commit comments

Comments
 (0)