Algorithms: Implement Merge Sort

This commit is contained in:
Manish 2023-08-22 10:53:39 +10:00
parent 016f31d703
commit 33c0806441

46
Algorithms/mergeSort.js Normal file
View File

@ -0,0 +1,46 @@
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-merge-sort
function mergeSort(array) {
// Only change code below this line
let merges = Math.floor(array.length / 2);
let mergeSize = 1;
let stop = false;
while (!stop) {
stop = merges ? false : true;
const array2 = [];
for (let i = 0; i <= merges; i++) {
const leftArrayStart = i * mergeSize * 2;
const rightArrayStart = leftArrayStart + mergeSize;
const leftArrayEnd = Math.min(rightArrayStart, array.length);
const rightArrayEnd = Math.min(rightArrayStart + mergeSize, array.length);
let leftI = leftArrayStart; // left array pointer
let rightI = rightArrayStart; // right array pointer
while (leftI < leftArrayEnd && rightI < rightArrayEnd) {
if (array[leftI] <= array[rightI]) {
array2.push(array[leftI++]);
} else {
array2.push(array[rightI++]);
}
}
while (leftI < leftArrayEnd) {
array2.push(array[leftI++]);
}
while (rightI < rightArrayEnd) {
array2.push(array[rightI++]);
}
}
array = array2;
mergeSize *= 2;
merges = Math.floor(merges / 2);
}
return array;
// Only change code above this line
}
console.log(mergeSort([4, 2, 1, 6, 5, 3, 0]));
console.log(
mergeSort([
1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92,
])
);