This is my code:
def sort_bubble(list):
comp_counter = 0
swap_counter = 0
n = len(list)
for i in range(n-1):
for j in range(n-i-1):
comp_counter += 1
if list[j] > list[j+1]:
swap_counter += 1
list[j], list[j+1] = list[j+1], list[j]
return comp_counter, swap_counter
It needs to bubble sort a list, and then return the proper amount of operations (time complexity).
I ran this code in two cases (each list had 20000 intergers):
a) Sorting an already sorted list (best case scenario): Number of comparsions = 49995000 = n(n-1)/2; Number of swaps = 0. Seems to me like something is wrong here, because number of comparsions in a best case scenario should be O(n) and the number of swaps O(1) (for a bubble sort algorithm).
b) Sorting a “backwards” sorted list (worst case scenario) : Number of comparsions = 49995000 = n(n-1)/2; Number of swaps = 49993762. In a worst case scenario this algorithm should have O(n^2) swaps and O(n^2) comparsions. Meanwhile the number of swaps and comparsions is something closer to O(n^2)/2
It is obvious to me that either my code, or my understanding of time complexity in algorithms is completely scuffed. Probably both. Would any of you nice gents explain what I’m doing wrong?
user24819857 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.