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:
parent
aca703c6de
commit
09df7526b1
@ -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²) |
|
@ -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 = 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
|
||||
}
|
Loading…
Reference in New Issue
Block a user