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
**Merge sort** is a divide-and-conquer algorithm based on the idea of breaking down a list into several sub-lists until each sublist consists of a single element and merging those sublists in a manner that results into a sorted list.
4
+
5
+
#### Idea:
6
+
- Divide the unsorted list into **N** sublists, each containing **1** element.
7
+
- Take adjacent pairs of two singleton lists and merge them to form a list of 2 elements. **N** will now convert into **N/2** lists of size 2.
8
+
- Repeat the process till a single sorted list of obtained.
9
+
10
+
While comparing two sub-lists for merging, the first element of both lists is taken into consideration. While sorting in ascending order, the element that is of a lesser value becomes a new element of the sorted list. This procedure is repeated until both the smaller sub-lists are empty and the new combined sub-list comprises all the elements of both the sub-lists.
*An example of merge sort. First divide the list into the smallest unit (1 element), then compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are sorted and merged. (image source-wikipedia)*
/*If a single list is empty the previous loop will be ended. But we also need to get the leftover from the another list. Following two will just grab the leftovers(if any) from the given two lists.*/
24
30
25
-
while(leftCount<left.length){
26
-
result.push(left[leftCount++]);
27
-
}
31
+
//take the leftovers from the left array(if any)
32
+
//Following loop can also replaced by a single line code like: result.concat(left.slice(leftCount, left.length))
33
+
while(leftCount<left.length){
34
+
result.push(left[leftCount++]);
35
+
}
28
36
29
-
while(rightCount<right.length){
30
-
result.push(right[rightCount++]);
31
-
}
37
+
//take the leftovers from the right array(if any)
38
+
//Following loop can also replaced by a single line code like: result.concat(right.slice(rightCount, right.length))
39
+
while(rightCount<right.length){
40
+
result.push(right[rightCount++]);
41
+
}
32
42
33
-
returnresult;
43
+
returnresult;
34
44
}
35
45
36
46
@@ -41,13 +51,13 @@ function merge(left, right){
41
51
* Using Math.round() will give you a non-uniform distribution!
42
52
*/
43
53
functiongetRandomInt(min,max){
44
-
returnMath.floor(Math.random()*(max-min+1))+min;
54
+
returnMath.floor(Math.random()*(max-min+1))+min;
45
55
}
46
56
47
57
vararr=[];
48
58
49
-
for(vari=0;i<10;i++){//initialize a random integer unsorted array
50
-
arr.push(getRandomInt(1,100));
59
+
for(vari=0;i<10;i++){//initialize a random integer unsorted array
0 commit comments