Skip to content

Commit c501ce6

Browse files
authored
Merge pull request vJechsmayr#100 from DAMMAK/feature/mergeSort
Merge Sort Completed
2 parents 4a83747 + f56e718 commit c501ce6

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

‎SortingAlgorithms/mergeSort.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
//@ts-check
2+
/**
3+
*@author Damola Adekoya
4+
* @param {Array} arr
5+
*/
6+
7+
const mergeSort = arr => {
8+
if (arr.length <= 1) return arr; //determine the end condition for recursive loop
9+
let mid = Math.floor(arr.length / 2);
10+
let left = mergeSort(arr.slice(0, mid));
11+
let right = mergeSort(arr.slice(mid, arr.length));
12+
return merge(left, right);
13+
};
14+
15+
/**
16+
*
17+
* @param {Array} arr1
18+
* @param {Array} arr2
19+
*/
20+
21+
const merge = (arr1, arr2) => {
22+
let result = []; //hold the new merge array
23+
let i = 0;
24+
let j = 0; //keep track of the current position in the loop
25+
while (i < arr1.length && j < arr2.length) {
26+
if (arr2[j] > arr1[i]) {
27+
result.push(arr1[i]);
28+
i++;
29+
} else {
30+
result.push[arr2[j]];
31+
j++;
32+
}
33+
}
34+
35+
// Push the leftover Array Element if arr1 and arr2 length not equal
36+
while (i < arr1.length) {
37+
result.push(arr1[i]);
38+
i++;
39+
}
40+
while (j < arr2.length) {
41+
result.push(arr2[j]);
42+
j++;
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
 (0)