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/bubble-sort

This commit is contained in:
Divlo 2021-06-29 20:05:54 +02:00
parent aca703c6de
commit 09df7526b1
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/bubble-sort
Created by [@Divlo](https://github.com/Divlo) on 29 June 2021.
| Algorithm | Best Case | Average Case | Worst Case |
| ----------------------------------------------------------- | ----------- | ------------ | ----------- |
| [Bubble sort](https://wikipedia.org/wiki/Bubble_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 = bubbleSort(numbers)
sortedNumbers.forEach((number) => {
console.log(number)
})
}
function bubbleSort (numbersInput) {
const numbers = [...numbersInput]
for (let index1 = 0; index1 < numbers.length; index1++) {
for (let index2 = 0; index2 < numbers.length - index1 - 1; index2++) {
if (numbers[index2] > numbers[index2 + 1]) {
const temporary = numbers[index2]
numbers[index2] = numbers[index2 + 1]
numbers[index2 + 1] = temporary
}
}
}
return numbers
}