mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2024-12-08 00:45:29 +01:00
feat(solutions): add sorting-algorithms/javascript/merge-sort
This commit is contained in:
parent
62c078d9a1
commit
aca703c6de
@ -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)) |
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
@ -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)
|
||||
}
|
Loading…
Reference in New Issue
Block a user