Bubble Sort Example in C with Code

Sorting algorithms are a cornerstone of computer science and programming. Among these, Bubble Sort stands out as one of the most straightforward and easy-to-grasp sorting methods. While it may not be the fastest option for handling large datasets, it serves as a fantastic starting point for understanding how sorting functions and how comparisons and swaps work within an array.

Blogging Illustration

In this blog, we’ll take a deep dive into a complete Bubble Sort example in C. We’ll explore how the algorithm operates, break down its step-by-step logic, and guide you through implementing it in C with a thorough explanation. Plus, you’ll find sample input and output, a dry run, optimization tips, and a collection of frequently asked questions at the end.

Whether you’re a student, a newcomer to C programming, or gearing up for coding interviews, this guide will be an invaluable resource. And if you’re eager to bolster your programming fundamentals even more, the C Programming Course in Noida by Uncodemy comes highly recommended.

What is Bubble Sort?

Bubble Sort is a straightforward comparison-based sorting algorithm that functions by repeatedly traversing the list, comparing adjacent elements, and swapping them if they’re out of order. This process continues until the list is fully sorted.

The name "bubble" sort comes from the way smaller elements gradually "bubble" up to the top of the list, while larger elements sink to the bottom through several iterations.

How Bubble Sort Works

Let’s break down how Bubble Sort works:

1. Compare the first two elements in the array.

2. If the first element is greater than the second, swap them.

3. Move to the next pair and repeat the comparison and swap if necessary.

4. Continue this process throughout the array.

5. With each pass, the largest unsorted element is moved to its rightful position.

6. Repeat the process for the remaining unsorted portion of the array.

7. This continues until no more swaps are needed, signaling that the array is sorted.

Example of Bubble Sort (Unsorted to Sorted)

Let’s break this down with a straightforward example.

Input Array:

[5, 3, 8, 4, 2]

Pass 1:

First, we compare 5 and 3 → We swap them → [3, 5, 8, 4, 2]

Next, we compare 5 and 8 → No swap needed here.

Then, we look at 8 and 4 → We swap → [3, 5, 4, 8, 2]

Finally, we compare 8 and 2 → Another swap → [3, 5, 4, 2, 8]

Pass 2:

Now, we compare 3 and 5 → No swap.

Next, we check 5 and 4 → We swap → [3, 4, 5, 2, 8]

Then, we compare 5 and 2 → We swap again → [3, 4, 2, 5, 8]

Pass 3:

We start with 3 and 4 → No swap here.

Next, we compare 4 and 2 → We swap → [3, 2, 4, 5, 8]

Pass 4:

Finally, we compare 3 and 2 → We swap → [2, 3, 4, 5, 8]

And just like that, the array is sorted!

Time Complexity of Bubble Sort

Grasping time complexity is crucial when diving into algorithms.

- Worst Case: O(n²)

- Best Case: O(n) – when the array is already sorted

- Average Case: O(n²)

Even though Bubble Sort has a quadratic time complexity, it serves as a great tool for teaching the fundamental concepts of sorting and comparisons.

Space Complexity

Bubble Sort is an in-place algorithm, which means it only needs a constant amount of extra space: O(1).

Bubble Sort Algorithm in C

Here's a C program that showcases how the bubble sort algorithm works.

#include 
 
void bubbleSort(int arr[], int n) {
	int i, j, temp;
	for (i = 0; i < n - 1; i++) {
    	// Flag to optimize and break if array is already sorted
    	int swapped = 0;
    	for (j = 0; j < n - i - 1; j++) {
        	if (arr[j] > arr[j + 1]) {
                // Swap adjacent elements if they are in wrong order
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
        	}
    	}
    	// If no two elements were swapped in the inner loop, break
    	if (!swapped)
            break;
	}
}
 
void printArray(int arr[], int size) {
	int i;
	for (i = 0; i < size; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
int main() {
	int arr[50], n, i;
 
    printf("Enter the number of elements: ");
    scanf("%d", &n);
 
    printf("Enter the elements:\n");
	for (i = 0; i < n; i++)
        scanf("%d", &arr[i]);
 
    printf("Unsorted Array:\n");
    printArray(arr, n);
 
    bubbleSort(arr, n);
 
    printf("Sorted Array:\n");
    printArray(arr, n);
 
	return 0;
}
                        

Sample Input and Output

Input

Enter the number of elements: 5
Enter the elements:
5 1 4 2 8

Output

Unsorted Array:
5 1 4 2 8
Sorted Array:
1 2 4 5 8

Dry Run with Detailed Steps

Let’s dry run the input [5, 1, 4, 2, 8]:

Pass 1:

5 > 1 → Swap → [1, 5, 4, 2, 8]
5 > 4 → Swap → [1, 4, 5, 2, 8]
5 > 2 → Swap → [1, 4, 2, 5, 8]
5 < 8 → No swap

Pass 2:

1 < 4 → No swap
4 > 2 → Swap → [1, 2, 4, 5, 8]
4 < 5 → No swap

Pass 3:

1 < 2 → No swap
2 < 4 → No swap

Now the array is sorted.

Optimized Bubble Sort

The optimized version of Bubble Sort adds a little twist by checking if any swaps have taken place during each pass. If no swaps occur, it means the array is already sorted, allowing the loop to exit early. This clever tweak helps cut down on unnecessary comparisons.

In the code provided, the variable `swapped` keeps track of whether any swaps have happened.

Pros and Cons of Bubble Sort

Advantages

- It's straightforward and easy to grasp.

- Works well for small datasets.

- Achieves linear performance (O(n)) in the best-case scenario when the array is already sorted.

Disadvantages

- Not ideal for larger datasets.

- Falls short in efficiency compared to other sorting algorithms like Merge Sort or Quick Sort.

Applications of Bubble Sort

While you won't find Bubble Sort in many production environments, it does have its moments of usefulness:

- Teaching and learning the basics of sorting logic.

- Verifying sorting logic in embedded systems with limited memory.

- Debugging small arrays during the development of algorithms.

- Practicing optimization techniques and understanding algorithm complexity.

Related Course

Looking to dive deep into C programming and tackle advanced sorting algorithms like Merge Sort, Quick Sort, and Insertion Sort? Check out the C Programming Course in Noida offered by Uncodemy!

This course is designed to cover the essentials of programming, data structures, and algorithms, complete with live coding sessions, real-world projects, and placement support. Whether you're just starting out or gearing up for tech interviews, this course will help you build a solid foundation.

Conclusion

Bubble Sort is one of the simplest sorting algorithms to grasp and implement. While it may not be the most efficient choice for larger arrays, it serves as a fantastic introduction to sorting, swapping, and nested loops. The principles behind Bubble Sort can be applied to more advanced sorting techniques as you progress in your studies.

In this blog, we took a closer look at how the Bubble Sort algorithm operates, crafted a complete Bubble Sort example in C, and guided you through it step-by-step with sample inputs. We also optimized the algorithm and weighed its advantages and disadvantages.

If you're eager to move beyond the basics and gain confidence in writing algorithms in C, consider signing up for the C Programming Course in Noida at Uncodemy. It’s a great way to enhance your programming career with hands-on support!

Frequently Asked Questions (FAQs)

Q1. What is Bubble Sort used for?

Bubble Sort is primarily used in educational environments to help students grasp the concepts behind sorting algorithms and comparisons. It can also be handy for systems that deal with very small data sets.

Q2. Why is Bubble Sort not efficient?

It has a time complexity of O(n²) for both the worst and average cases, which makes it quite inefficient when working with larger datasets.

Q3. Can Bubble Sort be optimized?

Absolutely! You can optimize it by introducing a flag variable to check if any swaps were made during the current pass. If no swaps occur, it means the array is already sorted.

Q4. Is Bubble Sort stable?

Yes, Bubble Sort is considered a stable sorting algorithm. It maintains the relative order of elements that have the same value.

Q5. What is the best-case time complexity of Bubble Sort?

The best-case time complexity is O(n), which happens when the array is already sorted.

Q6. What is the space complexity of Bubble Sort?

It's an in-place algorithm, which means it only requires O(1) additional space.

Q7. Where can I practice more sorting algorithms?

You can hone your skills in sorting algorithms by signing up for the C Programming Course in Noida offered by Uncodemy. This course provides access to a variety of exercises and hands-on projects.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses