Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 4330f18

Browse files
authored
merge sort in JS (#908)
1 parent ba924ec commit 4330f18

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Javascript/Algorithms/merge-sort.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function merge_Arrays(left_sub_array, right_sub_array) {
2+
let array = []
3+
while (left_sub_array.length && right_sub_array.length) {
4+
if (left_sub_array[0] < right_sub_array[0]) {
5+
array.push(left_sub_array.shift())
6+
} else {
7+
array.push(right_sub_array.shift())
8+
}
9+
}
10+
return [ ...array, ...left_sub_array, ...right_sub_array ]
11+
}
12+
function merge_sort(unsorted_Array) {
13+
const middle_index = unsorted_Array.length / 2
14+
if(unsorted_Array.length < 2) {
15+
return unsorted_Array
16+
}
17+
const left_sub_array = unsorted_Array.splice(0, middle_index)
18+
return merge_Arrays(merge_sort(left_sub_array),merge_sort(unsorted_Array))
19+
}
20+
unsorted_Array = [39, 28, 44, 4, 10, 83, 11];
21+
console.log("The sorted array will be: ",merge_sort(unsorted_Array));

0 commit comments

Comments
 (0)