You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// This algo uses two different functions and recursion.
6
+
7
+
// Merge two sorted array into a new sorted array.
8
+
functionmerge(left,right){
9
+
constresults=[];
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
+
functionmergeSort(arr){
25
+
if(arr.length<=1)returnarr;
26
+
27
+
letmidPoint=Math.floor(arr.length/2);
28
+
letleftArray=mergeSort(arr.slice(0,midPoint));
29
+
letrightArray=mergeSort(arr.slice(midPoint));
30
+
31
+
returnmerge(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).
0 commit comments