Bubble sort

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the intended order. It is called bubble sort because the movement of array elements is just like the movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the array elements in bubble sort move to the end in each iteration.

Although it is simple to use, it is primarily used as an educational tool because the performance of bubble sort is poor in the real world. It is not suitable for large data sets. The average and worst-case complexity of Bubble sort is O(n2), where n is a number of items.

Bubble short is majorly used where -

  • complexity does not matter
  • simple and shortcode is preferred

Algorithm

In the algorithm given below, suppose arr is an array of n elements. The assumed swap function in the algorithm will swap the values of given array elements.

1.     begin BubbleSort(arr)  

2.        for all array elements  

3.           if arr[i] > arr[i+1]  

4.              swap(arr[i], arr[i+1])  

5.           end if  

6.        end for     

7.        return arr     

8.     end BubbleSort  

  •  EXAMPLES OF BUBBLE SORT
EXAMPLE NO - 01


 EXAMPLE NO - 02

Bubble sort complexity

Now, let's see the time complexity of bubble sort in the best case, average case, and worst case. We will also see the space complexity of bubble sort.

1. Time Complexity

  • Best Case Complexity - It occurs when there is no sorting required, i.e. the array is already sorted. The best-case time complexity of bubble sort is O(n).
  • Average Case Complexity - It occurs when the array elements are in jumbled order that is not properly ascending and not properly descending. The average case time complexity of bubble sort is O(n2).
  • Worst Case Complexity - It occurs when the array elements are required to be sorted in reverse order. That means suppose you have to sort the array elements in ascending order, but its elements are in descending order. The worst-case time complexity of bubble sort is O(n2).

2. Space Complexity

  • The space complexity of bubble sort is O(1). It is because, in bubble sort, an extra variable is required for swapping.

Popular posts from this blog

DATA STRUCTURES-II

DATA STRUCTURES FOR B.TECH

DATA STRUCTURES FOR BCA