From cdf7ba502662b4428bd88141cf3efa0594662f61 Mon Sep 17 00:00:00 2001 From: Divlo Date: Tue, 29 Jun 2021 20:41:11 +0200 Subject: [PATCH] feat(solutions): add `sorting-algorithms/python/insertion-sort` --- .../solutions/python/bubble-sort/solution.py | 2 +- .../solutions/python/insertion-sort/README.md | 7 ++++++ .../python/insertion-sort/solution.py | 23 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 challenges/sorting-algorithms/solutions/python/insertion-sort/README.md create mode 100644 challenges/sorting-algorithms/solutions/python/insertion-sort/solution.py diff --git a/challenges/sorting-algorithms/solutions/python/bubble-sort/solution.py b/challenges/sorting-algorithms/solutions/python/bubble-sort/solution.py index f43b989..9f1540b 100644 --- a/challenges/sorting-algorithms/solutions/python/bubble-sort/solution.py +++ b/challenges/sorting-algorithms/solutions/python/bubble-sort/solution.py @@ -1,4 +1,4 @@ -from typing import List, Any +from typing import List import sys diff --git a/challenges/sorting-algorithms/solutions/python/insertion-sort/README.md b/challenges/sorting-algorithms/solutions/python/insertion-sort/README.md new file mode 100644 index 0000000..7776113 --- /dev/null +++ b/challenges/sorting-algorithms/solutions/python/insertion-sort/README.md @@ -0,0 +1,7 @@ +# sorting-algorithms/python/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²) | diff --git a/challenges/sorting-algorithms/solutions/python/insertion-sort/solution.py b/challenges/sorting-algorithms/solutions/python/insertion-sort/solution.py new file mode 100644 index 0000000..599e4cd --- /dev/null +++ b/challenges/sorting-algorithms/solutions/python/insertion-sort/solution.py @@ -0,0 +1,23 @@ +from typing import List +import sys + + +def insertion_sort(numbersInput: List[int]) -> List[int]: + numbers = list(numbersInput) + for index_1 in range(1, len(numbers)): + current = numbers[index_1] + index_2 = index_1 - 1 + while index_2 >= 0 and numbers[index_2] > current: + numbers[index_2 + 1] = numbers[index_2] + index_2 -= 1 + numbers[index_2 + 1] = current + return numbers + + +numbers: List[int] = [] +for value in sys.stdin: + numbers.append(int(value.rstrip('\n'))) + +sorted_numbers = insertion_sort(numbers) +for number in sorted_numbers: + print(number)