From 4c2c6ef429c002cf04e56f24ef5991f16ce9959a Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 28 Apr 2024 22:02:16 -0400 Subject: [PATCH] Goofing around with that intro to algorithms book again --- intro-to-algorithms/insertion_sort.py | 38 +++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 intro-to-algorithms/insertion_sort.py diff --git a/intro-to-algorithms/insertion_sort.py b/intro-to-algorithms/insertion_sort.py new file mode 100644 index 0000000..80e4158 --- /dev/null +++ b/intro-to-algorithms/insertion_sort.py @@ -0,0 +1,38 @@ +import os +import sys + + +def main() -> int: + in_ints: list[int] = [] + with open(sys.argv[1]) as infile: + for line in infile: + in_ints.append(int(line.strip())) + + insertion_sort(in_ints) + + for i in in_ints: + print(i) + + return 0 + + +def insertion_sort(in_ints: list[int]) -> None: + for i in range(len(in_ints) - 1): + j = i + 1 + key = in_ints[j] + + print(f"{in_ints} (save {key} from {j})", file=sys.stderr) + + while i > -1 and in_ints[i] > key: + in_ints[i + 1] = in_ints[i] + + print(f"{in_ints} (j={j} i={i})", file=sys.stderr) + + i -= 1 + + in_ints[i + 1] = key + print(f"{in_ints} (insert {key} at {i+1})", file=sys.stderr) + + +if __name__ == "__main__": + sys.exit(main())