Bubble Sort Algorithm

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. It is easy to understand but not efficient for large data.

How It Works

Code Example


for(int i = 0; i < n-1; i++){
  for(int j = 0; j < n-i-1; j++){
    if(arr[j] > arr[j+1]){
      int t = arr[j];
      arr[j] = arr[j+1];
      arr[j+1] = t;
    }
  }
}

Expected Output

Input: 5 3 1 Output: 1 3 5

When to Use