-
Notifications
You must be signed in to change notification settings - Fork 43
/
mergesort.js
60 lines (50 loc) · 1.8 KB
/
mergesort.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const mergeModule = ( () => {
// used to merge all of our pieces back together after recursively separating the array
const merge = ( left, right ) => {
// initialize array to return
const result = [];
// if both of our split arrays have items inside go through this while loop
while ( left.length > 0 && right.length > 0 ) {
// compare the first element of each array
if ( left[0] <= right[0] ) {
// if the left element is smaller, push it
// to our return array
result.push( left.shift() );
} else {
// if the right element is smaller, push it
// to our return array
result.push( right.shift() );
}
}
// if only our left array has an element left, push that
while ( left.length > 0 ) {
result.push( left.shift() );
}
// if only our right array has an element left, push that
while ( right.length > 0 ) {
result.push( right.shift() );
}
// return the sorted array
return result;
};
return {
mergeSort: function ( arr ) {
// Base Case - if the array is length 0 or 1,
// then we can assume it is already sorted and return it
if (arr.length < 2) {
return arr;
}
// pick a pivot at our the middle of our arr
const pivot = ( Math.floor(arr.length / 2) );
// separate the arr into two places, everything before it
const pLeft = arr.slice( 0, pivot );
// and everything after
const pRight = arr.slice( pivot, arr.length );
// call our mergeSort recursively on this array,
// splitting it further and further until it hits
// our base case and the array is split into lengths less than 2
return merge( this.mergeSort( pLeft ), this.mergeSort( pRight ));
},
};
});
module.exports = mergeModule;