Search code examples
time-complexitybubble-sort

How to analyse complexity of the given optimized bubble sort?


This is a pseudo code of optimized bubble sort algorithm. I have tried to analyze its time complexity, but i am not sure what is the cost of line 4 (if A[i-1] > A[i]). Is the answer (n-1)+(n-2)+........+1 ? Also what would be the cost of lines 5 to 8?

1.for j = A.length to 2
2.    swapped = false
3.    for i = 2 to j
4.        if A[i-1] > A[i]
5.            temp = A[i]
6.            A[i-1] = A[i]
7.            A[i-1] = temp
8.            swapped = true
9.    if(!swapped)
10.       break

Solution

  • The cost of lines 5 to 8 for a single iteration is O(1).

    The cost of loop at lines 3-8 is O(j-1).

    The cost of the whole sort in the worst case is O((n-1) + (n-2) + ... + 2) = O(n^2) (but of course in the best case, when the array is already sorted, the cost will be only O(n-1)).

    By the way, your implementation of optimized bubble sort contains an error: the if at line 9 should be inside the outer loop, but outside the inner.