How to implement Bubble sort

The Bubble sort is a simple sorting algorithm that continues to swap adjacent values, if they are in the incorrect order, until all the values are sorted.

The steps in the algorithm

To sort an array of size n in ascending order, it performs n-1 iterations and in each iteration:

  1. It scans through the entire array.
  2. It compares element at index i with the element at i+1.
  3. If the element at ​position i is greater than the element at i+1, then the elements are swapped.

On average, this algorithm takes O(n2)O(n^2) time (where n is the size of the array). The algorithm can be optimized to take O(n)O(n), if an array is already sorted in the required order, by breaking the outer for-loop if no element is swapped in the inner for-loop.

The following illustration shows the algorithm in action:

1 of 20

Implementation

Copyright ©2024 Educative, Inc. All rights reserved