Skip to content

Commit 8ab2795

Browse files
committed
Merge Sort using Javascript
1 parent 23780bb commit 8ab2795

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

merge_sort/javascript/mergeSort.js

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
const list = [5, 4, -3, 2, 1]
2+
3+
const mergeSort = (list) => {
4+
if (list.length <= 1) return list;
5+
const middle = list.length / 2;
6+
const left = list.slice(0, middle);
7+
const right = list.slice(middle, list.length);
8+
return merge(mergeSort(left), mergeSort(right));
9+
}
10+
11+
const merge = (left, right) => {
12+
var result = [];
13+
while (left.length || right.length) {
14+
if (left.length && right.length) {
15+
if (left[0] < right[0]) {
16+
result.push(left.shift())
17+
} else {
18+
result.push(right.shift())
19+
}
20+
} else if (left.length) {
21+
result.push(left.shift())
22+
} else {
23+
result.push(right.shift())
24+
}
25+
}
26+
return result;
27+
}
28+
29+
console.log(mergeSort(list))

0 commit comments

Comments
 (0)