top of page

Bubble Sort Concept

  • Writer: Ashok Kumar Kumawat
    Ashok Kumar Kumawat
  • Apr 25
  • 2 min read

Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order. After each pass, the largest element "bubbles up" to its correct position at the end.


C Code Example


#include <stdio.h>

int main() {
    int arr[5] = {5, 3, 8, 4, 2};  // Example array
    int i, j, temp;

	int n = sizeof(array) / sizeof(array[0]);

    printf("Original array: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    // Bubble Sort
    for(i = 0; i < n-1; i++) {
        for(j = 0; j < n-i-1; j++) {
            if(arr[j] > arr[j+1]) {
                // Swap
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }

    printf("\nSorted array: ");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Step-by-Step Example (Array: {5, 3, 8, 4, 2})

Pass 1:

  • Compare 5 and 3 → swap → {3, 5, 8, 4, 2}

  • Compare 5 and 8 → no swap

  • Compare 8 and 4 → swap → {3, 5, 4, 8, 2}

  • Compare 8 and 2 → swap → {3, 5, 4, 2, 8}   👉 Largest element (8) is now at the end.


Pass 2:

  • Compare 3 and 5 → no swap

  • Compare 5 and 4 → swap → {3, 4, 5, 2, 8}

  • Compare 5 and 2 → swap → {3, 4, 2, 5, 8}   👉 Second largest (5) is in place.


Pass 3:

  • Compare 3 and 4 → no swap

  • Compare 4 and 2 → swap → {3, 2, 4, 5, 8}   👉 Third largest (4) is in place.


Pass 4:

  • Compare 3 and 2 → swap → {2, 3, 4, 5, 8}   👉 Array is sorted!


Visual Representation (like images)

Think of each pass as bubbles rising:

Initial:   [5, 3, 8, 4, 2]

After Pass 1:   [3, 5, 4, 2, 8]

After Pass 2:   [3, 4, 2, 5, 8]

After Pass 3:   [3, 2, 4, 5, 8]

After Pass 4 (Final):   [2, 3, 4, 5, 8]

Recent Posts

See All
Q&A: C Code

Q1: How do you find the size of an array in C? Q2: What is an array of pointers in C, and why is it useful? Q3: How can function pointers be used to trigger callbacks in C? Q4: How can we determine th

 
 
 
Storage Classes in Embedded C

Excellent, let’s now systematically cover Storage Classes in Embedded C with the structured breakdown you asked for. 1. Concept Overview Storage classes define scope, lifetime, and visibility of varia

 
 
 
Macros — Complete Guide for Embedded C

What is a Macro and How It Works at Compilation Stage Macros are handled by the C Preprocessor, which runs before the actual compilation begins. The compilation pipeline looks like this: Source.c →

 
 
 

Comments


© 2035 by Robert Caro. Powered and secured by Wix

bottom of page