×
>
<

Data Structure

Bubble Sort | CrackEase

Bubble Sort

Bubble Sort

Sorting is the process of arranging data in some logical order. Bubble sort is a simple comparison-based algorithm for sorting linear data structures.

The logical order can be ascending or descending for numeric values or dictionary order for strings.

  1. Bubble Sort is simple and easy to implement.
  2. In bubble sort each adjacent pair of elements is compared.
  3. Elements are swapped if they are not in the desired order.
  4. The worst-case time complexity of bubble sort is O(n2).
Bubble sort pass 1
Bubble sort pass 2
Algorithm Explanation

The algorithm (for ascending order) works as follows:

  • Traverse the array from the start.
  • Compare each adjacent pair.
  • If the left element is greater than the right element, swap them.

That is: if arr[i] > arr[i+1] then swap.

Example pass-by-pass on array [28, 6, 4, 2, 24] (first pass shown):

  1. ( 28 6 4 2 24 ) → ( 6 28 4 2 24 ) — swapped 28 & 6
  2. ( 6 28 4 2 24 ) → ( 6 4 28 2 24 ) — swapped 28 & 4
  3. ( 6 4 28 2 24 ) → ( 6 4 2 28 24 ) — swapped 28 & 2
  4. ( 6 4 2 28 24 ) → ( 6 4 2 24 28 ) — swapped 28 & 24

After pass 1 the largest element (28) is at the end; subsequently each pass places the next-largest element in its correct position — like bubbles rising to the top.

Code of Bubble Sort
  
#include <stdio.h>

/* Function to print array */
void display(int arr[], int size) 
{ 
    int i; 
    for (i = 0; i < size; i++) 
        printf("%d ", arr[i]); 
    printf("\n"); 
} 

// Main function to run the program
int main() 
{ 
    int array[] = {5, 3, 1, 9, 8, 2, 4, 7}; 
    int size = sizeof(array) / sizeof(array[0]); 

    printf("Before bubble sort: \n");
    display(array, size);

    int i, j, temp; 
    for (i = 0; i < size - 1; i++) {       
       // After each iteration the rightmost i elements are sorted   
       for (j = 0; j < size - i - 1; j++) {
           if (array[j] > array[j + 1]) {
              temp = array[j]; // swap the elements
              array[j] = array[j + 1]; 
              array[j + 1] = temp; 
           }
       }
    }
    printf("After bubble sort: \n"); 
    display(array, size); 
    return 0; 
}
  
  
#include <iostream>
using namespace std;

void swap_vals(int *var1, int *var2)
{
    int temp = *var1;
    *var1 = *var2;
    *var2 = temp;
}

// Standard bubble sort implementation
void bubbleSort(int arr[], int n)
{
   int i, j;
   for (i = 0; i < n - 1; i++)
       // After each iteration rightmost i elements are sorted.
       for (j = 0; j < n - i - 1; j++) 
           if (arr[j] > arr[j + 1])
               swap_vals(&arr[j], &arr[j + 1]);
}

// Function to print array.
void display(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

// Main function to run the program.
int main()
{
    int array[] = {5, 3, 1, 9, 8, 2, 4, 7};
    int size = sizeof(array) / sizeof(array[0]);

    cout << "Before bubble sort: \n";
    display(array, size);

    bubbleSort(array, size);

    cout << "After bubble sort: \n";
    display(array, size);

    return 0;
}
  
  
// Time Complexity : O(n^2)
// Space Complexity : O(1)
class Main
{
    static void bubbleSort(int a[])
    {
        int len = a.length; // calculating the length of array
        for (int i = 0; i < len - 1; i++)
            for (int j = 0; j < len - i - 1; j++) 
                if (a[j] > a[j + 1]) // comparing the pair of elements
                {
                    // swapping a[j] and a[j+1]
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
    }

    /* Prints the array */
    static void printArray(int a[])
    {
        int len = a.length;
        for (int i = 0; i < len; i++)
            System.out.print(a[i] + " ");
        System.out.println();
    }

    // Main method to test above
    public static void main(String args[])
    {
        int arr[] = {5, 3, 1, 9, 8, 2, 4, 7};

        System.out.print("Before bubble sort:\n");
        printArray(arr);

        bubbleSort(arr);

        System.out.println("After bubble sort:");
        printArray(arr);
    }
}
	
	
Before bubble sort: 
5 3 1 9 8 2 4 7 
After bubble sort: 
1 2 3 4 5 7 8 9 
	
Bubble Sort — Optimized (early exit)

Optimization: If during a full pass no swaps occur, the array is already sorted — stop further passes.

  
#include <stdio.h>

void swap(int *var1, int *var2) 
{ 
    int temp = *var1; 
    *var1 = *var2; 
    *var2 = temp; 
} 

// Optimized bubble sort: stops early if already sorted
void bubbleSort(int arr[], int n) 
{ 
    int i, j; 
    for (i = 0; i < n - 1; i++) {
        int swapped = 0;

        // After each iteration rightmost i elements are sorted   
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
                swapped = 1;
            }
        }
        // if no swaps happened, array is sorted — break early
        if (!swapped)
            break;
    }
} 

/* Function to print array */
void display(int arr[], int size) 
{ 
    for (int i = 0; i < size; i++) 
        printf("%d ", arr[i]); 
    printf("\n"); 
} 

// Main function to run the program
int main() 
{ 
    int array[] = {10, 20, 30, 40, 50}; 
    int size = sizeof(array) / sizeof(array[0]); 

    printf("Before bubble sort: \n");
    display(array, size); 

    bubbleSort(array, size);

    printf("After bubble sort: \n"); 
    display(array, size); 
    return 0; 
}
  
  
#include <iostream>
using namespace std;

void swap_vals(int *var1, int *var2)
{
    int temp = *var1;
    *var1 = *var2;
    *var2 = temp;
}

// Optimized bubbleSort: stops early if no swaps occur
void bubbleSort(int arr[], int n)
{
   for (int i = 0; i < n - 1; i++)
   {
       bool swapped = false;

       for (int j = 0; j < n - i - 1; j++) 
       { 
           if (arr[j] > arr[j + 1]) {
               swap_vals(&arr[j], &arr[j + 1]);
               swapped = true;
           }
       }
       if (!swapped)
            break;
   }
}

void display(int arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main()
{
    int array[] = {10, 20, 30, 40, 50};
    int size = sizeof(array) / sizeof(array[0]);

    cout << "Before bubble sort: \n";
    display(array, size);

    bubbleSort(array, size);

    cout << "After bubble sort: \n";
    display(array, size);

    return 0;
}
  
  
// Time Complexity : O(n^2) (worst & average), O(n) best (optimized)
// Space Complexity : O(1)
class Main
{
    static void bubbleSort(int a[])
    {
        int len = a.length;
        for (int i = 0; i < len - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < len - i - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break;
        }
    }

    static void printArray(int a[])
    {
        for (int v : a) System.out.print(v + " ");
        System.out.println();
    }

    public static void main(String args[])
    {
        int arr[] = {10, 20, 30, 40, 50};

        System.out.print("Before bubble sort:\n");
        printArray(arr);

        bubbleSort(arr);

        System.out.println("After bubble sort:");
        printArray(arr);
    }
}
	
	
Before bubble sort: 
10 20 30 40 50 
After bubble sort: 
10 20 30 40 50 
	
Performance-Based Analysis of Bubble Sort Algorithm
Pros

  • Simple to understand and implement.
  • Works in-place (no extra memory required).
  • With the early-exit optimization best case becomes O(n).

Cons

  • Poor average and worst-case time complexity O(n2).
  • Not suitable for large datasets.

Interesting Facts

  1. Average and worst-case time complexity: O(n2).
  2. Best case (already sorted) with optimized version: O(n).
  3. Worst case: reverse-sorted array.

Number of comparisons reduces by 1 in each pass: total comparisons ≈ n(n-1)/2 in the unoptimized version.

Time Complexity Summary
BestAverageWorstSpace ComplexityComparisons (approx)
O(n)O(n2)O(n2)O(1)≈ n(n-1)/2
Footer Content | CrackEase