Page cover image

Bubble Sort

Bubble sort is a simple sorting algorithm that works by repeatedly comparing adjacent elements in an array and swapping them if they are in the wrong order.

The algorithm starts at the beginning of the array and compares the first two elements. If the first element is greater than the second element, the two elements are swapped. The algorithm then moves on to the next two elements and repeats the process. This continues until the end of the array is reached(j < n - i).

Use Case

In general, bubble sort should only be used when speed is not a major concern or when the array is already mostly sorted.

Question statement: https://www.codingninjas.com/studio/problems/bubble-sort_980524

Notes: https://drive.google.com/file/d/1DScaSvG0TzAy2b9MF9CcEtzoOxvai3MY/view

#include <bits/stdc++.h> 
void BubbleSort(vector<int>& arr, int n){
    for(int i = 1; i < n; i++){
        // for Round i to n-1
        bool isSorted = true; // condition for if the given array already sorted

        for(int j = 0; j < n-i; j++){
            // process elements till n-i index

            if(arr[j] > arr[j+1]){ 
                swap(arr[j], arr[j+1]);
                isSorted = false; // not sorted
            }
        }
        if(isSorted)
            break;
    }
}

Solved by Recursion

void bubbleSort(vector<int>& arr, int n){
    if(n == 0 || n == 1)
        return ;
    for(int i = 0; i < n-1; i++){
        if(arr[i] > arr[i+1])
            swap(arr[i], arr[i+1]);
    }
    bubbleSort(arr, n-1);
}

Code Explanation:

  1. The for loop iterates from 1 to n-1 (1<n), where n is the number of elements in the array.

  2. The bool variable isSorted is initialized to true. This variable will be used to track whether the array is already sorted.

  3. The for loop iterates from 0 to n-i-1 (O<n-i), where i is the current iteration of the outer loop.

  4. The if statement checks if the current element is greater than the next element. If it is, the two elements are swapped.

  5. The isSorted variable is set to false if the array is not sorted. This will cause the outer loop to continue iterating.

  6. The outer if statement checks if the array is sorted. If it is, the algorithm terminates.

Best Case: If any case comes where no. of swaps doesn't exit so, move out by breaking no need to do anything. Its Already shorted O(n).

The bubble sort algorithm is a very simple algorithm to understand and implement. However, it is also a very inefficient algorithm, with a worst-case time complexity of O(n^2). This means that the time it takes to sort an array using bubble sort grows quadratically with the size of the array. For this reason, bubble sort is not a good choice for sorting large arrays.

However, bubble sort can be a good choice for sorting small arrays or for sorting arrays that are already mostly sorted. In these cases, the inefficiency of bubble sort may not be a major concern.

Last updated

Was this helpful?