diff --git a/challenges/sorting-algorithms/solutions/javascript/merge-sort/README.md b/challenges/sorting-algorithms/solutions/javascript/merge-sort/README.md new file mode 100644 index 0000000..4c886b9 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/javascript/merge-sort/README.md @@ -0,0 +1,7 @@ +# sorting-algorithms/javascript/merge-sort + +Created by [@Divlo](https://github.com/Divlo) on 29 June 2021. + +| Algorithm | Best Case | Average Case | Worst Case | +| ----------------------------------------------------------- | ----------- | ------------ | ----------- | +| [Merge sort](https://wikipedia.org/wiki/Merge_sort) | O(n log(n)) | O(n log(n)) | O(n log(n)) | diff --git a/challenges/sorting-algorithms/solutions/javascript/merge-sort/package.json b/challenges/sorting-algorithms/solutions/javascript/merge-sort/package.json new file mode 100644 index 0000000..3dbc1ca --- /dev/null +++ b/challenges/sorting-algorithms/solutions/javascript/merge-sort/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/challenges/sorting-algorithms/solutions/javascript/merge-sort/solution.js b/challenges/sorting-algorithms/solutions/javascript/merge-sort/solution.js new file mode 100644 index 0000000..babc19b --- /dev/null +++ b/challenges/sorting-algorithms/solutions/javascript/merge-sort/solution.js @@ -0,0 +1,58 @@ +import readline from 'readline' + +const input = [] +const readlineInterface = readline.createInterface({ + input: process.stdin, + output: process.stdout +}) +readlineInterface.on('line', (value) => { + input.push(value) +}) +readlineInterface.on('close', solution) + +function solution() { + const numbers = input.map((value) => Number(value)) + const sortedNumbers = mergeSort(numbers) + sortedNumbers.forEach((number) => { + console.log(number) + }) +} + +function divideArray (numbers) { + const middle = Math.round(numbers.length / 2) + const left = numbers.slice(0, middle) + const right = numbers.slice(middle) + return [left, right] +} + +function merge (numbers1, numbers2) { + let indexNumbers1 = 0 + let indexNumbers2 = 0 + const result = [] + while (indexNumbers1 < numbers1.length && indexNumbers2 < numbers2.length) { + if (numbers1[indexNumbers1] < numbers2[indexNumbers2]) { + result.push(numbers1[indexNumbers1]) + indexNumbers1 += 1 + } else { + result.push(numbers2[indexNumbers2]) + indexNumbers2 += 1 + } + } + for (let index = indexNumbers1; index < numbers1.length; index++) { + result.push(numbers1[index]) + } + for (let index = indexNumbers2; index < numbers2.length; index++) { + result.push(numbers2[index]) + } + return result +} + +function mergeSort (numbers) { + if (numbers.length <= 1) { + return numbers + } + let [left, right] = divideArray(numbers) + left = mergeSort(left) + right = mergeSort(right) + return merge(left, right) +}