Skip to content

Commit 995b2f6

Browse files
committed
Merge sort code added
1 parent d560d56 commit 995b2f6

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Sorting/Merge Sort/merge-sort.js

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Merge Sort Implementation
2+
function mergeSort(arr){
3+
var len = arr.length;
4+
5+
if(len === 1) return arr;
6+
7+
var mid = Math.floor(len/2);
8+
var left = arr.slice(0, mid);
9+
var right = arr.slice(mid, len);
10+
11+
return merge(mergeSort(left), mergeSort(right));
12+
}
13+
14+
function merge(left, right){
15+
var result = [];
16+
var leftCount = 0, rightCount = 0;
17+
18+
while(leftCount < left.length && rightCount < right.length){
19+
if(left[leftCount] < right[rightCount])
20+
result.push(left[leftCount++]);
21+
else
22+
result.push(right[rightCount++]);
23+
}
24+
25+
while(leftCount < left.length){
26+
result.push(left[leftCount++]);
27+
}
28+
29+
while(rightCount < right.length){
30+
result.push(right[rightCount++]);
31+
}
32+
33+
return result;
34+
}
35+
36+
37+
/******************* Testing Merge sort algorithm *********************/
38+
39+
/**
40+
* Returns a random integer between min (inclusive) and max (inclusive)
41+
* Using Math.round() will give you a non-uniform distribution!
42+
*/
43+
function getRandomInt(min, max) {
44+
return Math.floor(Math.random() * (max - min + 1)) + min;
45+
}
46+
47+
var arr = [];
48+
49+
for(var i=0;i<10;i++){ //initialize a random integer unsorted array
50+
arr.push(getRandomInt(1, 100));
51+
}
52+
53+
console.log("Unsorted array: ");
54+
console.log(arr); //printing unsorted array
55+
56+
arr = mergeSort(arr);
57+
console.log("Sorted array: ");
58+
console.log(arr); //printing sorted array

0 commit comments

Comments
 (0)