mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2024-10-29 22:17:23 +01:00
feat(solutions): add sorting-algorithms/dart/insertion-sort
This commit is contained in:
parent
50a1cda3d8
commit
727bb97cab
@ -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²) |
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user