Complexity of bubble sort

For the first pass, in the worst case, we have to do n-1 comparison and swapping. For the n-1th pass, in the worst case, we have to do only one comparison and swapping. So, if we write it step by step then we will see:

Complexity = n - 1 + n - 2 + .......... + 2 + 1 = n * ( n - 1)/2 = O(n2)

Thus, the complexity of bubble sort is O(n2). However, there is some constant time required to assign a temporary variable, swapping, go through inner loops, and so on. We can ignore them since they are constant.

Here is the time complexity table for bubble sort, for best, average, and worst case scenarios:

Best time complexity

Ω(n)

Worst time complexity

O(n2)

Average time complexity

Θ(n2)

Space complexity (worst case)

O(1)

Though the time complexity is O(n2) for bubble sort, we can still apply some improvements to reduce the number of comparison and swaps. Let's now explore those options. The best time is Ω(n) since we need at least one inner loop to run to find out that the array is already sorted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset