I am new to math and algortithms and very confused. I am looking for the amount of times the numbers get compared in n. in my head it goes like this. if n = 3 in the worst case scenario: [3,2,1] 3 gets compared to 2 and swapped -> [2,3,1] 2 gets compared to 3, 3 gets compared to 1 and swaps -> [2,1,3] 2 gets compared to 1 and swapped [1,2,3] 1 gets compared to 2, 2 gets compared to 3. Done. I get 6 comparisons in this instance.
but in a bubble sort in the worst case there should be as many comparisons as swaps. Can someone explain this to me.
def my_sort(lst):
lst_sorted = lst.copy()
n = len(lst_sorted)
change = True
while change:
change = False
for j in range(n - 1):
if lst_sorted[j] > lst_sorted[j + 1]:
lst_sorted[j], lst_sorted[j + 1] = lst_sorted[j + 1], lst_sorted[j]
change = True
return lst_sorted
i have looked at n*(n-1)/2 which makes it 3 but i have also seen n*(n+1)/2 or even O(n^2).
thank you in advance.
Your understanding is correct.
The worst-case scenario for a bubble sort algorithm involves determining the maximum number of comparisons needed to sort an array of elements (i.e., arrange them in ascending order).
To achieve this, the algorithm starts with comparing and swapping adjacent elements, moving the largest unsorted element to its correct position in each pass. In your example, the largest element is 3. The algorithm iteratively moves it along the array one step at a time until it reaches its correct position at the end of the array.
This process is repeated for the next largest element, which in your case is 2. The algorithm swaps it with adjacent elements until it reaches a position where the element to its right is larger. This continues for each element in the array until the entire array is sorted in ascending order.
So, in summary, the algorithm doesn't just start with the largest element once; it performs multiple passes through the array, ensuring that the largest unsorted element is moved to its correct position in each pass.