Add missing solutions for algorithm challenges (#38858)

This commit is contained in:
Ty Mick
2020-07-15 13:03:29 -04:00
committed by GitHub
parent cd90da13f0
commit aa1acbe68f
2 changed files with 57 additions and 2 deletions

View File

@ -79,7 +79,37 @@ function isSorted(arr) {
<section id='solution'>
```js
// solution required
function mergeSort(array) {
if (array.length === 1) {
return array;
} else {
const splitIndex = Math.floor(array.length / 2);
return merge(
mergeSort(array.slice(0, splitIndex)),
mergeSort(array.slice(splitIndex))
);
}
// Merge two sorted arrays
function merge(array1, array2) {
let merged = [];
while (array1.length && array2.length) {
if (array1[0] < array2[0]) {
merged.push(array1.shift());
} else if (array1[0] > array2[0]) {
merged.push(array2.shift());
} else {
merged.push(array1.shift(), array2.shift());
}
}
// After looping ends, one array is empty, and other array contains only
// values greater than all values in `merged`
return [...merged, ...array1, ...array2];
}
}
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
</section>

View File

@ -75,7 +75,32 @@ function isSorted(arr) {
<section id='solution'>
```js
// solution required
function quickSort(array) {
if (array.length === 0) {
return [];
} else {
const pivotValue = array[0];
// Sort elements into three piles
let lesser = [];
let equal = [];
let greater = [];
for (let e of array) {
if (e < pivotValue) {
lesser.push(e);
} else if (e > pivotValue) {
greater.push(e);
} else {
equal.push(e);
}
}
return [...quickSort(lesser), ...equal, ...quickSort(greater)];
}
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</section>