diff --git a/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-merge-sort.english.md b/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-merge-sort.english.md index a2ef0507f2..d9748ddd6e 100644 --- a/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-merge-sort.english.md +++ b/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-merge-sort.english.md @@ -79,7 +79,37 @@ function isSorted(arr) {
```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]); ```
diff --git a/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-quick-sort.english.md b/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-quick-sort.english.md index 5f535a2cea..4c56ff2137 100644 --- a/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-quick-sort.english.md +++ b/curriculum/challenges/english/10-coding-interview-prep/algorithms/implement-quick-sort.english.md @@ -75,7 +75,32 @@ function isSorted(arr) {
```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] ```