|
| 1 | +# Insertion Sort |
| 2 | +# 🟢 Easy |
| 3 | +# |
| 4 | +# https://www.algoexpert.io/questions/insertion-sort |
| 5 | +# |
| 6 | +# Tags: Sorting |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +# The problem asks us to implement this naive sorting algorithm. |
| 13 | +# |
| 14 | +# Time complexity: O(n^2) - Nested loops that iterate over n elements. |
| 15 | +# Space complexity; O(1) - Only extra constant space. |
| 16 | +class Naive: |
| 17 | + def insertionSort(self, array: List[int]) -> List[int]: |
| 18 | + # Start sorting from index i to the end. |
| 19 | + for i in range(1, len(array)): |
| 20 | + # Check value pairs starting at the last on the sorted |
| 21 | + # section and moving back to the first two. |
| 22 | + for j in range(i, 0, -1): |
| 23 | + if array[j] < array[j - 1]: |
| 24 | + array[j], array[j - 1] = array[j - 1], array[j] |
| 25 | + return array |
| 26 | + |
| 27 | + |
| 28 | +def test(): |
| 29 | + executors = [ |
| 30 | + Naive, |
| 31 | + ] |
| 32 | + tests = [ |
| 33 | + [[1], [1]], |
| 34 | + [[1, 2], [1, 2]], |
| 35 | + [[8, 5, 2, 9, 5, 6, 3], [2, 3, 5, 5, 6, 8, 9]], |
| 36 | + ] |
| 37 | + for executor in executors: |
| 38 | + start = timeit.default_timer() |
| 39 | + for _ in range(1): |
| 40 | + for col, t in enumerate(tests): |
| 41 | + sol = executor() |
| 42 | + result = sol.insertionSort(t[0]) |
| 43 | + exp = t[1] |
| 44 | + assert result == exp, ( |
| 45 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 46 | + + f" test {col} using \033[1m{executor.__name__}" |
| 47 | + ) |
| 48 | + stop = timeit.default_timer() |
| 49 | + used = str(round(stop - start, 5)) |
| 50 | + cols = "{0:20}{1:10}{2:10}" |
| 51 | + res = cols.format(executor.__name__, used, "seconds") |
| 52 | + print(f"\033[92m» {res}\033[0m") |
| 53 | + |
| 54 | + |
| 55 | +test() |
0 commit comments