The Bubble Sort Algorithm
you may wonder why I post this section here while it's not a LAB. Simply, to show you how to know the number of swaps happened to rearrange the list.
Sorting a list
How many passes do we need to sort the entire list?The code is already written. I just added one thing, did you notice? Yes, a variable called swaps, and I assigned it to 0 value. Then, swaps variable is inserted under the for loop, if block. So; whenever the if condition is True (which means that the arranging order is not correct), we add 1 to swaps.
Solution Code:
my_list = [8, 10, 6, 2, 4] # list to sort
swapped = True # It's a little fake, we need it to enter the while loop.
swaps = 0 # To count the number of loops happened to arrange the list in order
while swapped:
swapped = False # no swaps so far
for i in range(len(my_list) - 1):
if my_list[i] > my_list[i + 1]:
swaps += 1 #Each loop add 1 to swaps variable
swapped = True # a swap occurred!
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
print(f"My list: {my_list} , Number of swaps: {swaps}")
0 Comments
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.