Insertion Sort
Insertion sort is a sorting algorithm that proceeds from left to right. It creates a "sorted" side by picking a number from the "unsorted" side of the array, then 'inserting' it into the correct sorted position in the "sorted" side of the array:

I used two counters; "i" to go through the array and select the number to be sorted, then "j" to go through and compare the selected number to every number before it, i.e. the "sorted" list. All that's needed is to check if you're already at the leftmost number with "j", at which point you just need to insert the number to the first element.
def insertion(numblimit, amountlimit):
numberlist = []
i = 0
while i < amountlimit:
numberlist.append(random.randint(1, numblimit))
i += 1
print("initial: ", numberlist)
i = 1
while i < len(numberlist):
j = i-1
while True:
if j == -1:
swap = numberlist.pop(i)
numberlist.insert(0, swap)
break
elif numberlist[i] >= numberlist[j]:
break
elif numberlist[j] > numberlist[i] >= numberlist[j - 1]:
swap = numberlist.pop(i)
numberlist.insert(j, swap)
break
else:
j -= 1
i += 1
return numberlist
Comments
Post a Comment