Skip to content

Commit

Permalink
live merge
Browse files Browse the repository at this point in the history
  • Loading branch information
leafoflegend committed Mar 11, 2024
1 parent ec08413 commit 9bce687
Showing 1 changed file with 40 additions and 24 deletions.
64 changes: 40 additions & 24 deletions reacto/merge_sort.js
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)));

0 comments on commit 9bce687

Please sign in to comment.