Bubble sort

Bubble sort works by comparing two numbers right next to each other and swapping them if the bigger number is on the left. The simplest sort but also the most inefficient. You just need one counter to count through, and when you're doing the comparison, just do counter+1. You break the loop once there hasn't been a swap.
def bubble(numblimit, amountlimit):
numberlist = []
i = 0
while i < amountlimit:
numberlist.append(random.randint(1, numblimit))
i += 1
print("initial: ", numberlist)
i = 0
swap = 1
while swap == 1:
swap = 0
for x in range(0, len(numberlist)-1):
if numberlist[x] > numberlist[x+1]:
temp = numberlist[x]
numberlist[x] = numberlist[x+1]
numberlist[x+1] = temp
swap = 1
break
return numberlist
Comments
Post a Comment