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:
parent
09df7526b1
commit
d1c9a7ef3e
@ -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²) |
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user