1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-12-08 00:45:29 +01:00

feat(solutions): add sorting-algorithms/javascript/insertion-sort

This commit is contained in:
Divlo 2021-06-29 20:08:05 +02:00
parent 09df7526b1
commit d1c9a7ef3e
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
3 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# sorting-algorithms/javascript/insertion-sort
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.
| Algorithm | Best Case | Average Case | Worst Case |
| ----------------------------------------------------------- | ----------- | ------------ | ----------- |
| [Insertion sort](https://wikipedia.org/wiki/Insertion_sort) | O(n) | O(n²) | O(n²) |

View File

@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@ -0,0 +1,33 @@
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 = insertionSort(numbers)
sortedNumbers.forEach((number) => {
console.log(number)
})
}
function insertionSort(numbersInput) {
const numbers = [...numbersInput]
for (let index1 = 1; index1 < numbers.length; index1++) {
const current = numbers[index1]
let index2 = index1 - 1
while (index2 >= 0 && numbers[index2] > current) {
numbers[index2 + 1] = numbers[index2]
index2 -= 1
}
numbers[index2 + 1] = current
}
return numbers
}