Goofing around with that intro to algorithms book again
This commit is contained in:
parent
e5166ee912
commit
4c2c6ef429
38
intro-to-algorithms/insertion_sort.py
Normal file
38
intro-to-algorithms/insertion_sort.py
Normal file
@ -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())
|
Loading…
Reference in New Issue
Block a user