1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2024-07-18 02:20:12 +02:00

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

This commit is contained in:
Divlo 2021-06-29 22:40:45 +02:00
parent 50a1cda3d8
commit 727bb97cab
No known key found for this signature in database
GPG Key ID: 185ED2F15F104E52
2 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,7 @@
# sorting-algorithms/dart/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,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 = insertionSort(numbers);
for (int index = 0; index < length; index++) {
print(sortedNumbers[index]);
}
}
List<int> insertionSort(Iterable<int> numbersInput) {
var numbers = [...numbersInput];
for (var index1 = 0; index1 < numbers.length; index1++) {
var current = numbers[index1];
var index2 = index1 - 1;
while (index2 >= 0 && numbers[index2] > current) {
numbers[index2 + 1] = numbers[index2];
index2 -= 1;
}
numbers[index2 + 1] = current;
}
return numbers;
}
String readLineSync() {
String? string = stdin.readLineSync();
return string == null ? '' : string;
}