Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1c2a69d

Browse files
author
Swastikyadav
committed
Implement mergeSort algo
1 parent 58f6c7a commit 1c2a69d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎DsAlgo-Questions/29-mergeSort.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Sort a given array using MergeSort.
3+
*/
4+
5+
// This algo uses two different functions and recursion.
6+
7+
// Merge two sorted array into a new sorted array.
8+
function merge(left, right) {
9+
const results = [];
10+
11+
while (left.length && right.length) {
12+
if (left[0] < right[0]) {
13+
results.push(left.shift());
14+
} else {
15+
results.push(right.shift());
16+
}
17+
}
18+
19+
// By this time, either left or right is an empty array.
20+
return [...results, ...left, ...right];
21+
}
22+
23+
// Divide an array into pairs (recursively) and use the above merge function to get a new sorted array. (Divide and conquer)
24+
function mergeSort(arr) {
25+
if (arr.length <= 1) return arr;
26+
27+
let midPoint = Math.floor(arr.length / 2);
28+
let leftArray = mergeSort(arr.slice(0, midPoint));
29+
let rightArray = mergeSort(arr.slice(midPoint));
30+
31+
return merge(leftArray, rightArray);
32+
}
33+
34+
console.log(mergeSort([6, 3, 60, 0, 40, -40]));
35+
36+
/*
37+
Time Complexity of Merge Sort Algorithm
38+
Let's try to calculate time complexity of merge sort algorithm. So, taking our previous example ([6, 3, 5, 2]), it took 2 steps to divide it into multiple single element array.
39+
40+
**
41+
42+
It took 2 steps to divide an array of length 4 - (2^2)
43+
44+
**.
45+
46+
Now if we double the length of array (8), it will take 3 steps to divide - (2^3). Means doubling the array length didn't doubled the steps.
47+
48+
Hence time complexity of merge sort algorithm is Logarithmic Time Complexity O(log n).
49+
*/

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /