fix(linter): merge sort JavaScript (#272)
parent
1e85e00602
commit
34d7f59beb
|
@ -1,32 +1,28 @@
|
||||||
function merge(left, right) {
|
function merge(left, right) {
|
||||||
let arr = []
|
const arr = [];
|
||||||
// Break out of loop if any one of the array gets empty
|
// Break out of loop if any one of the array gets empty
|
||||||
while (left.length && right.length) {
|
while (left.length && right.length) {
|
||||||
// Pick the smaller among the smallest element of left and right sub arrays
|
// Pick the smaller among the smallest element of left and right sub arrays
|
||||||
if (left[0] < right[0]) {
|
if (left[0] < right[0]) {
|
||||||
arr.push(left.shift())
|
arr.push(left.shift());
|
||||||
} else {
|
} else {
|
||||||
arr.push(right.shift())
|
arr.push(right.shift());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Concatenating the leftover elements
|
|
||||||
// (in case we didn't go through the entire left or right array)
|
|
||||||
return [ ...arr, ...left, ...right ]
|
|
||||||
}
|
|
||||||
|
|
||||||
function mergeSort(array) {
|
|
||||||
const half = array.length / 2
|
|
||||||
|
|
||||||
// Base case or terminating case
|
|
||||||
if(array.length < 2){
|
|
||||||
return array
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const left = array.splice(0, half)
|
|
||||||
return merge(mergeSort(left),mergeSort(array))
|
|
||||||
}
|
|
||||||
|
|
||||||
//testing
|
// Concatenating the leftover elements
|
||||||
array = [4, 8, 7, 2, 11, 1, 3];
|
// (in case we didn't go through the entire left or right array)
|
||||||
console.log(mergeSort(array));
|
return [...arr, ...left, ...right];
|
||||||
|
}
|
||||||
|
function mergeSort(array) {
|
||||||
|
const half = array.length / 2;
|
||||||
|
|
||||||
|
// Base case or terminating case
|
||||||
|
if (array.length < 2) {
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
const left = array.splice(0, half);
|
||||||
|
return merge(mergeSort(left), mergeSort(array));
|
||||||
|
}
|
||||||
|
// testing
|
||||||
|
console.log(mergeSort([4, 8, 7, 2, 11, 1, 3]));
|
||||||
|
|
Loading…
Reference in New Issue