-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ec08413
commit 9bce687
Showing
1 changed file
with
40 additions
and
24 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,34 +1,50 @@ | ||
function merge(left, right) { | ||
let arr = []; | ||
const merge = (left, right) => { | ||
const sortedArr = []; | ||
|
||
// Break out of loop if any one of the array gets empty | ||
while (left.length && right.length) { | ||
|
||
// Pick the smaller among the smallest element of left and right arrays | ||
if (left[0] < right[0]) { | ||
arr.push(left.shift()); | ||
} | ||
else { | ||
arr.push(right.shift()); | ||
if (left[0] <= right[0]) { | ||
sortedArr.push(left.shift()); | ||
} else { | ||
sortedArr.push(right.shift()); | ||
} | ||
} | ||
|
||
// Concatenating the leftover elements | ||
return [...arr, ...left, ...right]; | ||
} | ||
const combinedArr = [...sortedArr, ...left, ...right]; | ||
|
||
console.log('Combined: ', combinedArr); | ||
|
||
return combinedArr; | ||
}; | ||
|
||
// MS [3, 2, 4, 1] | ||
// MS [3, 2] | ||
// MS [3] | ||
// MS [2] | ||
// M ([3], [2]) => [2, 3] | ||
// MS [4, 1] | ||
// MS [4] | ||
// MS [1] | ||
// M ([4], [1]) => [1, 4] | ||
// M ([2, 3], [1, 4]) => [1, 2, 3, 4] | ||
const mergeSort = (listOfNumbers) => { | ||
if (listOfNumbers.length < 2) { | ||
return listOfNumbers; | ||
} | ||
|
||
function mergeSort(array) { | ||
const half = Math.round(array.length / 2); | ||
const halfPoint = Math.round(listOfNumbers.length / 2); | ||
|
||
// Base case or stopping condition | ||
if (array.length < 2) { | ||
return array; | ||
} | ||
const left = listOfNumbers.splice(0, halfPoint); | ||
const right = listOfNumbers; | ||
|
||
console.log('Left: ', left, 'Right: ', right); | ||
|
||
const left = array.splice(0, half); // array of first half | ||
const right = array; // array of second half | ||
return merge(mergeSort(left), mergeSort(right)); | ||
}; | ||
|
||
return merge(mergeSort(left), mergeSort(right)); // Recursive call | ||
} | ||
const generateArray = (size) => { | ||
return new Array(size).fill('').map(() => { | ||
return Math.round(Math.random() * 1000); | ||
}); | ||
}; | ||
|
||
console.log(mergeSort([3, 1, 7, -2, 15, 0, 100, 2])); | ||
console.log('Final Result: ', mergeSort(generateArray(25))); |