Search code examples
algorithmsortingbubble-sort

bubble sort algorithm find time complexity


i am trying to find the time complexity of the bubble sort

n=length[A]
for j <- n-1 to 1
for i <- 0 to j-1
if A[i]>a[i+1]
temp=A[i]
A[i]=A[i+1]
A[i+1]=temp

return A 

please any one can help thanks


Solution

    • In line 1 we are assigning length of array to n so constant time
    • In line 2 we have a for loop that decrements j by 1 every iteration until j=1 and in total will iterate n-2 times.
    • Inside the first for loop we have a second for loop that increments i by 1 every iteration until i=j-1 and will iterate j-1 times. On each iteration of the inner for loop we have lines 4,5,6,7 which are all just assignments and array access which cost, in total, constant time.
    • We can think about the two for loops in the following way: For every iteration of the outer for loop, the inner for loop will iterate j-1 times.
    • Therefore on the first iteration of the outer for loop, we have j = n-1. That means the inner for loop will iterate (n-1)-1 = (n-2) times. Then on the second iteration of the outer for loop we have j= n-2 so the inner for loop will iterate (n-2)-1 = (n-3) times and so on. And we do this until j = 1.
    • We will then have the equation: (n-2) + (n-3) + ... + 2 + 1 which is the total number of times the inner loop will iterate after the entire algorithm executes. We know that 1 + 2 + ... + n-1 + n = n(n-1)/2 so our expression can be simplified to this: n(n-1)/2 -(n-1) -n = n(n-1)/2 -2n + 1 = O(n^2).
    • Since our inner for loop will iterate O(n^2) times, and on each iteration do constant work, then that means our runtime will be O(cn^2) where c is the amount of constant work done by lines 4,5,6,7. Combine O(cn^2) with line 1 which is O(1) we have O(cn^2) + O(1) which is just O(n^2).
    • Therefore runtime of BubbleSort is O(n^2).

    If you are still confused then maybe this will help: https://www.youtube.com/watch?v=Jdtq5uKz-w4