Sorting/insertion.py

54 lines
1.2 KiB
Python

"""
Insertion Sort
by BBaoVanC
This import uses the insertion method of sorting.
Pros:
Fast for small lists
Cons:
Gets increasingly slower once you get past a certain amount of numbers
"""
def sort(A):
for j in range(1, len(A)):
# print(j)
key = A[j]
i = j - 1
while i >= 0 and A[i] > key:
A[i + 1] = A[i]
i = i - 1
A[i + 1] = key
# print(str(A))
return A
if __name__ == '__main__':
from timeit import default_timer as timer
with open("nums.txt") as f:
A = f.readlines()
A = [x.strip() for x in A]
A = [int(x) for x in A]
start = timer()
A = sort(A)
elapsed_time = timer() - start
print("TIME: %.16f" % elapsed_time)
# print("Opening file")
f = open("sort_insertion.txt", "w+")
nums2 = list()
for item in A:
item = str(item) + "\n" # add newline character to each item in the nums2 list...
nums2.append(item) # ...
nums2[-1] = nums2[-1].strip() # remove newline character from last item in list
for item in nums2:
# print("Writing number: " + item)
f.write(item) # write each number to the file
# print("Closing file")
f.close()
# print("FINISHED")