Skip to content

Commit c42ba80

Browse files
authored
Merge pull request ashutosh97#74 from miketu926/mergesort
Added Merge Sort
2 parents 6647b02 + e97bfd9 commit c42ba80

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

Mergesort-JS/mergeSort.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const myArray = [2, 4, 1, 6, -7, 8, 5, 9, 3, 4];
2+
3+
const mergeSort = (arr) => {
4+
if (arr.length <= 1) {
5+
return arr;
6+
}
7+
8+
let midIdx = Math.floor(arr.length / 2);
9+
let left = arr.slice(0, midIdx);
10+
let right = arr.slice(midIdx);
11+
12+
let leftSorted = mergeSort(left);
13+
let rightSorted = mergeSort(right);
14+
15+
return merge(leftSorted, rightSorted);
16+
17+
};
18+
19+
const merge = (arr1, arr2) => {
20+
let merged = [];
21+
22+
while (arr1.length && arr2.length) {
23+
if (arr1[0] < arr2[0]) {
24+
merged.push(arr1.shift());
25+
} else {
26+
merged.push(arr2.shift());
27+
}
28+
}
29+
30+
return [...merged, ...arr1, ...arr2];
31+
};
32+
33+
console.log(mergeSort(myArray));

Mergesort-JS/question.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Sort the given by implementing Quicksort
2+
[2, 4, 1, 6, -7, 8, 5, 9, 3, 4]
3+
4+
answer:
5+
[ -7, 1, 2, 3, 4, 4, 5, 6, 8, 9 ]

0 commit comments

Comments
 (0)