Bubble Sort in Data Structure: Algorithm and Time Complexity

Chapter 43 • Data Structure
Bubble Sort in Data Structure: Algorithm and Time Complexity

Understand Bubble Sort with simple explanations, step-by-step examples, a complete dry run, optimized C programming, time and space complexity, and interactive practice.

Beginner Friendly Complete Dry Run C Program Interactive Practice Exam Questions

Sorting is an important topic in Data Structure because it helps us arrange information in a meaningful order. Students often understand sorting in theory but get confused when they have to perform comparisons and swaps in an actual algorithm.

Bubble Sort is one of the easiest algorithms to learn because it follows a simple rule: compare two neighbouring elements and swap them if they are in the wrong order.

The main difficulty starts when students are asked to write every pass, count the comparisons, calculate the time complexity or explain the C program in an examination.

In this chapter, we will understand Bubble Sort in Data Structure from the beginning. We will learn its working, algorithm, dry run, optimized version, C implementation, complexity and common exam questions.

Quick Answer: What Is Bubble Sort in Data Structure?

Bubble Sort is a comparison-based sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. In ascending sorting, the largest remaining element moves to its correct position after each pass. Optimized Bubble Sort takes O(n) time in the best case, O(n²) time in the average and worst cases, and O(1) extra space.

01 / Introduction

What Is Bubble Sort in Data Structure?

Bubble Sort in Data Structure: Algorithm and Time Complexity

Bubble Sort is a sorting technique in which neighbouring elements are compared repeatedly. If the first element is larger than the second element, their positions are exchanged when sorting in ascending order.

This process continues until all the elements are arranged in the correct order.

It is called Bubble Sort because larger values gradually move towards the end of the array, similar to bubbles rising towards the surface of water.

Simple Bubble Sort Example

Consider an array containing five values:

Before Sorting
29 10 14 37 13
↓
After Bubble Sort
10 13 14 29 37

The array is arranged in ascending order.

Important Characteristics of Bubble Sort

  • It is a comparison-based sorting algorithm.
  • It compares adjacent elements.
  • It swaps elements when necessary.
  • It sorts an array in place.
  • It is stable when equal values are not swapped.
  • It is simple but inefficient for large arrays.

Remember: Bubble Sort does not find the smallest element directly like Selection Sort. It compares neighbouring elements and moves larger values gradually towards the end.

02 / Working principle

How Does Bubble Sort Work?

Bubble Sort works through repeated passes. A pass means moving through the unsorted portion of the array and comparing each pair of neighbouring elements.

For ascending order, the algorithm performs a swap whenever the left element is greater than the right element.

Working Steps of Bubble Sort

  1. Start from the first element of the array.
  2. Compare the current element with the next element.
  3. If the first is greater than the second, swap them.
  4. Move to the next adjacent pair.
  5. Continue until the largest remaining element reaches the end of the unsorted part.
  6. Repeat the process for the remaining unsorted elements.
  7. Stop when a complete pass makes no swaps, or all required passes are completed.

Understanding Compare and Swap

Suppose we have only two elements: 29 and 10.

Compare the Two Elements
29 10

Is 29 greater than 10? Yes.

↓ Swap
10 29

The smaller element moves left, and the larger element moves right.

This single comparison is easy. Bubble Sort simply repeats the same process for the remaining pairs.

03 / Numerical example

Bubble Sort Example with Step-by-Step Dry Run

This is one of the most important parts of Bubble Sort. In many semester exams, students are asked to sort a given array and show the result after each pass.

Let us sort the following array in ascending order:

29 10 14 37 13

Pass 1: Compare Adjacent Elements

The first pass compares four pairs because the array contains five elements.

Comparison Action Array After Comparison
29 and 10 Swap 10, 29, 14, 37, 13
29 and 14 Swap 10, 14, 29, 37, 13
29 and 37 No swap 10, 14, 29, 37, 13
37 and 13 Swap 10, 14, 29, 13, 37
Array After Pass 1
10 14 29 13 37

The largest element, 37, has reached its final position.

Pass 1 performs four comparisons and three swaps.

Pass 2: Sort the Remaining Elements

We do not need to compare with 37 again because it is already in its final position.

Before: 10 14 29 13 37 10 and 14 → No swap 14 and 29 → No swap 29 and 13 → Swap After: 10 14 13 29 37

Pass 2 performs three comparisons and one swap. Now 29 is also in its final position.

Pass 3: Continue Sorting

Before: 10 14 13 29 37 10 and 14 → No swap 14 and 13 → Swap After: 10 13 14 29 37

Pass 3 performs two comparisons and one swap.

Pass 4: Check the Remaining Pair

Before: 10 13 14 29 37 10 and 13 → No swap After: 10 13 14 29 37

No swap occurs in Pass 4. The optimized algorithm can stop because the array is sorted.

Complete Bubble Sort Pass Table

Pass Array After Pass Comparisons Swaps
1 10, 14, 29, 13, 37 4 3
2 10, 14, 13, 29, 37 3 1
3 10, 13, 14, 29, 37 2 1
4 10, 13, 14, 29, 37 1 0
Total Sorted 10 5
Final Answer

Sorted Array: 10, 13, 14, 29, 37. The optimized implementation performs 10 comparisons and 5 swaps for this input.

Exam Tip: Do not confuse comparisons with swaps. Every checked pair counts as a comparison, but a swap happens only if those elements are in the wrong order.

04 / Algorithm

Bubble Sort Algorithm in Data Structure

The algorithm below sorts an array in ascending order using the basic Bubble Sort method.

Simple Bubble Sort Algorithm

Algorithm: BubbleSort(A, n)

1. Start

2. For i = 0 to n - 2

3.     For j = 0 to n - i - 2

4.         If A[j] > A[j + 1]

5.             Swap A[j] and A[j + 1]

6.         End If

7.     End For

8. End For

9. Stop

Explanation of the Algorithm

Outer Loop: Controls the number of passes.

Inner Loop: Compares adjacent elements in the unsorted portion of the array.

Condition: If the left element is greater than the right element, swapping is required.

Swap: Exchanges the positions of two elements.

Why Does the Inner Loop Become Shorter?

After the first pass, the largest value is already at the end. After the second pass, the second-largest value is also in its correct position.

Therefore, the inner loop does not need to check the sorted portion again.

Pass 1: n - 1 comparisons Pass 2: n - 2 comparisons Pass 3: n - 3 comparisons ... Final pass: 1 comparison

This is why the usual inner-loop condition depends on both n and the outer-loop counter i.

05 / Improved algorithm

Optimized Bubble Sort Algorithm

Basic Bubble Sort performs all its scheduled passes even when the array becomes sorted early.

This wastes comparisons, especially when the array is already sorted or nearly sorted.

Optimized Bubble Sort introduces a variable called swapped.

At the beginning of each pass, this variable is set to false. Whenever two elements are swapped, it becomes true.

If an entire pass finishes without a swap, the algorithm knows that the array is sorted and stops.

Optimized Bubble Sort Pseudocode

Algorithm: OptimizedBubbleSort(A, n)

For i = 0 to n - 2

    swapped = false

    For j = 0 to n - i - 2

        If A[j] > A[j + 1]

            Swap A[j], A[j + 1]

            swapped = true

        End If

    End For

    If swapped == false

        Break

    End If

End For

Example: Already Sorted Array

Input: 10 20 30 40 50 Pass 1: 10 20 30 40 50 Swaps = 0 Stop.

Since no swapping is required, the optimized algorithm stops after the first pass.

It performs only four comparisons for five elements.

Basic vs Optimized Bubble Sort

Feature Basic Bubble Sort Optimized Bubble Sort
Working Performs scheduled passes Stops after a pass without swaps
Best-case time O(n²) O(n)
Average time O(n²) O(n²)
Worst-case time O(n²) O(n²)
Extra space O(1) O(1)
Already sorted input Continues passes Stops after first pass

Important: The O(n) best-case time complexity belongs to the optimized Bubble Sort with early termination. Without that optimization, the basic version still performs quadratic comparisons.

06 / Performance analysis

Bubble Sort Time Complexity

Time complexity tells us how the running work of an algorithm grows as the number of elements increases.

Bubble Sort uses repeated comparisons, so its performance depends on the number and arrangement of elements.

Best Case O(n), optimized
Average Case O(n²)
Worst Case O(n²)
Extra Space O(1)
Stable Yes
In-Place Yes

1. Best-Case Time Complexity: O(n)

The best case occurs when the array is already sorted and the optimized algorithm uses the swapped flag.

Input: 1 2 3 4 5 Comparisons = 4 Swaps = 0 Time Complexity = O(n)

The algorithm scans the array once, finds no swaps and terminates.

2. Worst-Case Time Complexity: O(n²)

The worst case occurs when the array is in reverse order for the required ascending sorting.

Input: 5 4 3 2 1 Pass 1: 4 comparisons Pass 2: 3 comparisons Pass 3: 2 comparisons Pass 4: 1 comparison Total = 4 + 3 + 2 + 1 Total Comparisons = 10 Total Swaps = 10

For an array containing n elements, the maximum comparison count in this standard implementation is:

C(n) = (n - 1) + (n - 2) + ... + 1 C(n) = n(n - 1) / 2 C(n) = (n² - n) / 2 Therefore: Worst-Case Time = O(n²)

The quadratic term dominates as n becomes large.

3. Average-Case Time Complexity: O(n²)

In the average case, elements are usually arranged in a mixed order. Bubble Sort still needs many comparisons and swaps before the array becomes sorted.

Therefore, its average-case time complexity is O(n²).

Bubble Sort Comparisons by Array Size

Number of Elements Maximum Comparisons
510
1045
20190
501,225
1004,950
1,000499,500

This table shows why Bubble Sort becomes inefficient for large input sizes.

Bubble Sort Space Complexity

Bubble Sort does not need another array to arrange values. It exchanges elements within the original array.

The iterative implementation uses only a few extra variables, including loop counters, a temporary variable and the swapped flag.

Auxiliary Space = O(1)

This is called constant extra space because the number of additional variables does not increase with the array size.

Common Mistake: O(1) extra space does not mean the input array takes no memory. It means Bubble Sort uses only constant additional working memory.

07 / Important properties

Is Bubble Sort Stable and In-Place?

Yes. Standard Bubble Sort is stable when it swaps only elements that are strictly out of order.

Stability of Bubble Sort

A stable sorting algorithm preserves the original relative order of elements having equal sorting keys.

Suppose three students have the following marks:

Before: A (80), B (65), C (80) After Stable Sorting: B (65), A (80), C (80)

Students A and C have equal marks. Their original relative order remains unchanged.

Bubble Sort preserves this order when its swap condition uses the strict comparison operator >.

What Happens If We Use >= Instead?

Swapping elements with equal keys can change their original relative order, so the standard stability guarantee is lost.

Is Bubble Sort In-Place?

Yes. Bubble Sort directly rearranges elements inside the original array without requiring another array proportional to the input size.

Number of Swaps and Inversions

There is another useful property of Bubble Sort. When adjacent elements are swapped only because they are out of order, every swap removes exactly one inversion.

An inversion is a pair of elements that appear in the wrong relative order for ascending sorting.

In our example 29, 10, 14, 37, 13, there are five inversions. Therefore, Bubble Sort performs exactly five swaps.

Inversion pairs: (29, 10) (29, 14) (29, 13) (14, 13) (37, 13) Total Inversions = 5 Total Adjacent Swaps = 5

Extra Concept: The number of swaps in standard adjacent-swap Bubble Sort equals the original array's inversion count. The number of comparisons can still be larger than the number of swaps.

08 / Interactive learning

Interactive Bubble Sort Visualizer

Understanding Bubble Sort becomes easier when you can see every comparison and swap.

Use the following interactive visualizer to enter your own numbers and watch how Bubble Sort arranges them.

Enter 3 to 8 whole numbers separated by commas. Allowed values: -99 to 999.

0 Comparisons
0 Swaps
0 Pass

Ready to start Bubble Sort.

Practice: First try 29, 10, 14, 37, 13. Then try 5, 4, 3, 2, 1 and finally 1, 2, 3, 4, 5. Compare the number of swaps and comparisons in each case.

09 / Practical programming

Bubble Sort Program in C

The following C program implements optimized Bubble Sort. It accepts values from the user, sorts them in ascending or descending order and displays the array after each pass.

The program also counts the total comparisons and swaps. This helps students connect the code with its time complexity.

Complete C Program

#include <stdio.h>

#define MAX 100

int main(void) {

    int a[MAX], n, order;

    long long comparisons = 0;
    long long swaps = 0;

    printf("Enter number of elements (1-100): ");

    if (scanf("%d", &n) != 1 ||
        n < 1 || n > MAX) {

        puts("Invalid array size.");
        return 1;
    }

    printf("Enter %d integers: ", n);

    for (int i = 0; i < n; i++) {

        if (scanf("%d", &a[i]) != 1) {

            puts("Invalid integer input.");
            return 1;
        }
    }

    printf("Enter 1 for ascending or 2 for descending: ");

    if (scanf("%d", &order) != 1 ||
        (order != 1 && order != 2)) {

        puts("Invalid order choice.");
        return 1;
    }

    for (int i = 0; i < n - 1; i++) {

        int swapped = 0;

        for (int j = 0; j < n - i - 1; j++) {

            comparisons++;

            if ((order == 1 && a[j] > a[j + 1]) ||
                (order == 2 && a[j] < a[j + 1])) {

                int temp = a[j];

                a[j] = a[j + 1];

                a[j + 1] = temp;

                swapped = 1;
                swaps++;
            }
        }

        printf("Pass %d: ", i + 1);

        for (int k = 0; k < n; k++) {
            printf("%d ", a[k]);
        }

        putchar('\n');

        if (!swapped) {
            break;
        }
    }

    printf("Sorted array: ");

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

    printf("\nComparisons: %lld\nSwaps: %lld\n",
           comparisons, swaps);

    return 0;
}

Sample Input

Enter number of elements (1-100): 5

Enter 5 integers:
29 10 14 37 13

Enter 1 for ascending or 2 for descending: 1

Output of Bubble Sort C Program

Pass 1: 10 14 29 13 37
Pass 2: 10 14 13 29 37
Pass 3: 10 13 14 29 37
Pass 4: 10 13 14 29 37

Sorted array: 10 13 14 29 37

Comparisons: 10
Swaps: 5

Explanation of the C Program

1. Reading Input

The program asks the user how many elements should be sorted and then reads those integer values.

2. Selecting Sorting Order

The user enters 1 for ascending order or 2 for descending order.

3. Outer Loop

The outer loop controls the sorting passes. After each pass, one more element reaches its correct position.

4. Inner Loop

The inner loop compares adjacent elements in the unsorted part of the array.

5. Swap Condition

For ascending order, the elements are swapped when the first is greater than the second.

For descending order, swapping occurs when the first is smaller than the second.

6. Optimized Termination

The swapped variable records whether a swap occurred during the pass. If no swapping is needed, the program stops early.

7. Comparison and Swap Counters

The comparisons counter increases for every adjacent-pair comparison. The swaps counter increases only when two elements exchange positions.

Program Verification: This C program was compiled using GCC with C11 and tested for ascending, descending, already sorted and reverse sorted input arrays.

How to Run Bubble Sort in C

  1. Open VS Code or another C editor.
  2. Create a file named bubble_sort.c.
  3. Paste the C program into the file.
  4. Compile it with a C compiler.
  5. Run the executable and enter your values.

For GCC, the compilation command is:

gcc -std=c11 -Wall -Wextra bubble_sort.c -o bubble_sort

On Windows PowerShell with GCC, run the compiled program using:

.\bubble_sort.exe
10 / Evaluation

Advantages and Disadvantages of Bubble Sort

Advantages

  • Simple to understand and implement.
  • Useful for learning comparisons and swaps.
  • Requires O(1) auxiliary space.
  • Stable with the correct swap condition.
  • Optimized version can stop early.
  • Works directly on the original array.

Disadvantages

  • O(n²) average-case time complexity.
  • Slow for large arrays.
  • May perform many swaps.
  • Less efficient than many advanced sorting methods.
  • Usually not preferred for large production datasets.

Applications of Bubble Sort

Bubble Sort is mainly useful for educational purposes, small demonstration programs and situations where simple sorting logic is more important than performance.

It is often used in programming classes to introduce loops, arrays, comparisons, swapping and basic algorithm analysis.

Practical Advice: Bubble Sort is excellent for understanding how sorting works, but for real applications involving large datasets, a suitable library sorting function or a more efficient algorithm is usually a better choice.

11 / Comparison

Bubble Sort vs Selection Sort vs Insertion Sort

These three algorithms are commonly taught together because they are relatively easy to understand.

Feature Bubble Selection Insertion
Working Swap neighbours Select minimum Insert into sorted part
Best Time O(n), optimized O(n²) O(n)
Average Time O(n²) O(n²) O(n²)
Worst Time O(n²) O(n²) O(n²)
Extra Space O(1) O(1) O(1)
Stable Yes No, standard version Yes

Bubble Sort moves larger values towards the end through adjacent swaps. Selection Sort repeatedly selects the minimum value.

Insertion Sort inserts each new value into an already sorted portion. It is generally more useful than Bubble Sort when a small array is nearly sorted.

12 / Common mistakes

Common Mistakes in Bubble Sort

Mistake Correct Explanation
Comparing non-adjacent values Standard Bubble Sort compares neighbouring elements.
Writing every comparison as a swap Swap only when the required ordering condition is violated.
Using an incorrect loop boundary The inner loop must not access an index beyond the array.
Always writing best case O(n) O(n) requires an early-exit optimisation.
Swapping equal-key records Avoid equal-key swaps to preserve stability.
Thinking the array needs O(n) extra space The iterative algorithm uses O(1) auxiliary space.

Common C Programming Error

Students sometimes use this incorrect condition:

for (int j = 0; j < n; j++) {
    if (a[j] > a[j + 1]) {
        /* swap */
    }
}

When j reaches the final valid index, a[j + 1] accesses memory beyond the array boundary.

The correct inner-loop condition for the usual Bubble Sort is:

for (int j = 0; j < n - i - 1; j++) {
    /* compare adjacent elements */
}

Programming Tip: Array indices in C start from zero. An array containing n elements has valid indices from 0 to n - 1.

13 / University exam preparation

Important Bubble Sort Questions and Answers

The following questions are useful for semester exams, viva preparation and revision. The marks indicate suggested answer lengths, not verified previous-year question papers.

2 Marks: Define Bubble Sort.

Bubble Sort is a comparison-based sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order.

2 Marks: What Is the Worst-Case Time Complexity of Bubble Sort?

The worst-case time complexity of Bubble Sort is O(n²). This occurs when the array requires the maximum number of comparisons and swaps, such as a reverse-sorted array for ascending sorting.

2 Marks: Why Is Bubble Sort Called Stable?

Bubble Sort is stable because equal-key elements retain their original relative order when the algorithm swaps only strictly out-of-order pairs.

5 Marks: Explain Bubble Sort with an Example.

Bubble Sort repeatedly compares adjacent elements and swaps them if they are not in the required order.

For the array 29, 10, 14, 37, 13, the first pass produces 10, 14, 29, 13, 37.

The process continues until the final array becomes 10, 13, 14, 29, 37.

Its average and worst-case time complexity is O(n²), while its auxiliary space complexity is O(1).

5 Marks: Explain Optimized Bubble Sort.

Optimized Bubble Sort uses an additional variable called swapped. At the beginning of every pass, it is set to false.

Whenever a swap occurs, the variable becomes true. If no swap occurs during a complete pass, the algorithm stops early.

This improvement gives O(n) best-case time when the input is already sorted.

10 Marks: Explain Bubble Sort Algorithm, Example and Complexity.

Bubble Sort is a simple comparison-based sorting algorithm used to arrange data in ascending or descending order.

It repeatedly compares adjacent elements and swaps them when required. After every complete pass in ascending order, the largest remaining element reaches its final position.

The algorithm uses an outer loop for passes and an inner loop for comparisons.

For an array of n elements, the maximum number of comparisons is n(n - 1)/2.

Therefore, average and worst-case time complexity is O(n²). The best case becomes O(n) when early termination is used.

Bubble Sort requires O(1) additional space and is stable when equal-key elements are not swapped. It is easy to implement but inefficient for large datasets.

14 / Practice questions

Bubble Sort Practice Questions with Solutions

Question 1: Sort 9, 4, 7, 2 Using Bubble Sort.

Show Step-by-Step Solution

Pass 1: 4, 7, 2, 9.

Pass 2: 4, 2, 7, 9.

Pass 3: 2, 4, 7, 9.

Final sorted array: 2, 4, 7, 9.

Question 2: What Is the Best-Case Time of Optimized Bubble Sort?

A. O(1)
B. O(n)
C. O(n²)
D. O(log n)

Show Answer

B. O(n). An already sorted array needs one comparison pass and no swaps.

Question 3: Which Elements Are Compared in Bubble Sort?

A. Only first and last
B. Random elements
C. Adjacent elements
D. Only minimum elements

Show Answer

C. Adjacent elements. Bubble Sort compares neighbouring positions.

Question 4: Calculate the Maximum Comparisons for n = 8.

Show Calculation

Maximum comparisons = n(n - 1)/2.

= 8 × 7 / 2 = 28.

Answer: 28 comparisons.

Question 5: What Happens When No Swapping Occurs During a Pass?

Show Answer

The optimized algorithm concludes that the array is already sorted and terminates without additional passes.

15 / Frequently asked questions

FAQs About Bubble Sort in Data Structure

What is Bubble Sort in simple words?

Bubble Sort is an algorithm that repeatedly checks two neighbouring values and swaps them when they are not in order.

What is the time complexity of Bubble Sort?

Optimized Bubble Sort has O(n) best-case time and O(n²) average and worst-case time complexity.

What is the space complexity of Bubble Sort?

Its iterative implementation uses O(1) extra space because it sorts elements inside the original array.

Is Bubble Sort stable?

Yes. Standard Bubble Sort is stable when equal elements are not swapped.

What is the difference between Bubble Sort and Quick Sort?

Bubble Sort repeatedly compares adjacent elements. Quick Sort partitions an array around a pivot. Quick Sort usually performs better on large inputs, although its standard worst-case time is O(n²).

Why is Bubble Sort inefficient?

Bubble Sort may perform a quadratic number of comparisons and swaps, especially when the data is in reverse order.

Can Bubble Sort arrange data in descending order?

Yes. Reverse the comparison rule so that smaller values move towards the right.

16 / Quick revision

Bubble Sort Quick Revision Notes

Definition

Compare and swap adjacent elements.

Best Case

O(n) with early exit.

Average Case

O(n²).

Worst Case

O(n²).

Extra Space

O(1).

Stable

Yes, with strict comparisons.

Bubble Sort Memory Trick

Compare → Swap → Move Right → Repeat Largest value reaches the end after each full pass. No swap in a pass → Stop.

Remember this sequence and practise one dry run. It will help you understand both the algorithm and its C implementation.

17 / Continue learning

Related Data Structure Concepts

Bubble Sort is based on simple step-by-step algorithmic instructions. If you want to revise the basic meaning of algorithms, read Algorithm in Data Structure: Characteristics, Steps and Examples .

For further study of Bubble Sort, you can also refer to Programiz: Bubble Sort .

Conclusion

Bubble Sort in Data Structure becomes easier when you understand the simple rule of comparing two neighbouring elements and swapping them when needed.

After every pass, the largest remaining value moves to its correct position in ascending sorting. The optimized version can stop early if the array is already sorted.

For exams, practise the dry run, understand the loop conditions, write the C program yourself and revise the best, average and worst-case complexities.

Once you understand Bubble Sort, other sorting techniques such as Selection Sort and Insertion Sort will become easier to learn.

Chapter 43 — Completed

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Join Telegram Exam updates and free resources