Home » Full Stack Development » Bubble Sort in C with Example and Code

Bubble Sort in C with Example and Code

Bubble Sort in C: Definition, Algorithm, and Examples

Bubble Sort is a simple sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This process continues until the array is sorted. It is named โ€œBubbleโ€ because the largest element bubbles up to the end of the array in each pass.


Working of Bubble Sort

  1. Compare the first two elements.
  2. If the first element is greater than the second, swap them.
  3. Move to the next pair and repeat.
  4. Continue until the end of the array (1 pass complete).
  5. Repeat the process for (n-1) passes until array is sorted.

Algorithm of Bubble Sort

procedure bubbleSort(arr, n):
    for i = 0 to n-1:
        for j = 0 to n-i-2:
            if arr[j] > arr[j+1]:
                swap arr[j] and arr[j+1]

C Program for Bubble Sort

#include <stdio.h>

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

void printArray(int arr[], int n) {
    for (int i=0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    printf("Unsorted array: ");
    printArray(arr, n);
    bubbleSort(arr, n);
    printf("Sorted array: ");
    printArray(arr, n);
    return 0;
}

Dry Run Example

Letโ€™s sort the array: {5, 3, 8, 4, 2}

PassArray State
Pass 13, 5, 4, 2, 8
Pass 23, 4, 2, 5, 8
Pass 33, 2, 4, 5, 8
Pass 42, 3, 4, 5, 8

Time Complexity

CaseTime Complexity
Best Case (Already Sorted)O(n)
Average CaseO(n2)
Worst Case (Reverse Sorted)O(n2)

Space Complexity

O(1) โ†’ Bubble sort is an in-place sorting algorithm.


Leave a comment

Your email address will not be published. Required fields are marked *