mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2025-05-18 12:02:53 +02:00
feat(solutions): add sorting-algorithms/dart/bubble-sort
This commit is contained in:
@ -0,0 +1,7 @@
|
||||
# sorting-algorithms/dart/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,32 @@
|
||||
import 'dart:io';
|
||||
|
||||
void main() {
|
||||
int length = int.parse(readLineSync());
|
||||
List<int> numbers = [];
|
||||
for (int indexInput = 0; indexInput < length; indexInput++) {
|
||||
numbers.add(int.parse(readLineSync()));
|
||||
}
|
||||
List<int> sortedNumbers = bubbleSort(numbers);
|
||||
for (int index = 0; index < length; index++) {
|
||||
print(sortedNumbers[index]);
|
||||
}
|
||||
}
|
||||
|
||||
List<int> bubbleSort(Iterable<int> numbersInput) {
|
||||
var numbers = [...numbersInput];
|
||||
for (var index1 = 0; index1 < numbers.length; index1++) {
|
||||
for (var index2 = 0; index2 < numbers.length - index1 - 1; index2++) {
|
||||
if (numbers[index2] > numbers[index2 + 1]) {
|
||||
var temporary = numbers[index2];
|
||||
numbers[index2] = numbers[index2 + 1];
|
||||
numbers[index2 + 1] = temporary;
|
||||
}
|
||||
}
|
||||
}
|
||||
return numbers;
|
||||
}
|
||||
|
||||
String readLineSync() {
|
||||
String? string = stdin.readLineSync();
|
||||
return string == null ? '' : string;
|
||||
}
|
Reference in New Issue
Block a user