DS Sorting

Bubble Sort Algorithm

Bubble Sort Algorithm: An Overview

Bubble Sort is one of the simplest sorting algorithms. It repeatedly swaps adjacent elements until the entire list is sorted. This algorithm is often introduced to students as it frequently appears in exams.

How Bubble Sort Works

Bubble Sort works by repeatedly comparing and swapping adjacent elements if they are in the wrong order. This process continues until the array is fully sorted. The name comes from the way larger elements "bubble" to the top, similar to air bubbles rising in water.

Algorithm Implementation

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.

begin BubbleSort(arr) for all array elements if arr[i] > arr[i+1] swap(arr[i], arr[i+1]) end if end for return arr end BubbleSort

Video explanation of Bubble Sort algorithm

Performance and Usage

Although easy to understand and implement, Bubble Sort is inefficient for large datasets. Its average and worst-case time complexity is O(n²), making it impractical for large-scale applications.

When to Use Bubble Sort?

  • When performance is not a concern.
  • When a simple and easy-to-understand algorithm is needed
Bubble Sort Algorithm Visualization