- What is bubble sort and how it works
- How to implement bubble sort in C
- How bubble sort compares and swaps adjacent elements
- How to optimize bubble sort
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to sort an array using the bubble sort algorithm.
Bubble sort is the simplest sorting algorithm. It works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The process is repeated until the list is sorted.
š” Key Point: Bubble sort gets its name because smaller elements "bubble" to the top of the list, like bubbles rising to the surface of water.
Bubble sort is used in many real-world applications, such as:
- Education: Teaching sorting algorithm concepts
- Small Datasets: Sorting small lists where simplicity is more important than efficiency
- Visualizations: Creating sorting algorithm visualizations
- Embedded Systems: Where simplicity is preferred over performance
Visual Example
Let's see how bubble sort sorts the array [64, 34, 25, 12, 22, 11, 90]:
Pass 1:
[64, 34, 25, 12, 22, 11, 90] ā Compare 64 & 34 ā Swap ā [34, 64, 25, 12, 22, 11, 90] [34, 64, 25, 12, 22, 11, 90] ā Compare 64 & 25 ā Swap ā [34, 25, 64, 12, 22, 11, 90] [34, 25, 64, 12, 22, 11, 90] ā Compare 64 & 12 ā Swap ā [34, 25, 12, 64, 22, 11, 90] [34, 25, 12, 64, 22, 11, 90] ā Compare 64 & 22 ā Swap ā [34, 25, 12, 22, 64, 11, 90] [34, 25, 12, 22, 64, 11, 90] ā Compare 64 & 11 ā Swap ā [34, 25, 12, 22, 11, 64, 90] [34, 25, 12, 22, 11, 64, 90] ā Compare 64 & 90 ā No swap ā [34, 25, 12, 22, 11, 64, 90] After Pass 1: [34, 25, 12, 22, 11, 64, 90] (90 is in correct position)
Pass 2:
[34, 25, 12, 22, 11, 64, 90] ā After comparisons, 64 is in correct position [25, 12, 22, 11, 34, 64, 90]
Final Sorted Array:
[11, 12, 22, 25, 34, 64, 90]
C Program for Bubble Sort
#include <stdio.h>
int main() {
int n, i, j, temp;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort Algorithm
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Display sorted array
printf("\nSorted array in ascending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sample Output
Enter the number of elements: 7 Enter 7 elements: 64 34 25 12 22 11 90 Sorted array in ascending order: 11 12 22 25 34 64 90
Another Example:
Enter the number of elements: 5 Enter 5 elements: 5 1 4 2 8 Sorted array in ascending order: 1 2 4 5 8
Example with Negative Numbers:
Enter the number of elements: 6 Enter 6 elements: -5 10 -2 8 0 -10 Sorted array in ascending order: -10 -5 -2 0 8 10
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;ā number of elementsint i, j;ā loop countersint temp;ā temporary variable for swapping
- Get User Input: Reads the array elements from the user.
- Bubble Sort:
- Outer Loop:
for(i = 0; i < n-1; i++)ā runs n-1 times - Inner Loop:
for(j = 0; j < n-i-1; j++)ā compares adjacent elements - Comparison: If
arr[j] > arr[j+1], swap them - After each pass, the largest element "bubbles" to the end
- Outer Loop:
- Display Result: Prints the sorted array.
- Return:
return 0;indicates successful program execution.
š Note: Bubble sort has a time complexity of O(n²). It is not efficient for large arrays but is great for learning sorting concepts.
Bubble Sort Algorithm
Step-by-step algorithm:
- Start
- Read the array elements
- For
i = 0ton-2:- For
j = 0ton-i-2:- If
arr[j] > arr[j+1]:- Swap
arr[j]andarr[j+1]
- Swap
- If
- For
- Print the sorted array
- End
Optimized Bubble Sort
We can optimize bubble sort by adding a flag to check if any swaps were made in a pass. If no swaps were made, the array is already sorted and we can break early.
#include <stdio.h>
int main() {
int n, i, j, temp;
int swapped;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Optimized Bubble Sort
for(i = 0; i < n-1; i++) {
swapped = 0;
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;
swapped = 1;
}
}
// If no swaps were made, array is already sorted
if(swapped == 0) {
break;
}
}
printf("\nSorted array in ascending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sample Output:
Enter the number of elements: 5 Enter 5 elements: 1 2 3 4 5 Sorted array in ascending order: 1 2 3 4 5 (Only one pass needed since array was already sorted)
Time and Space Complexity
| Scenario | Time Complexity | Space Complexity |
|---|---|---|
| Best Case (Already Sorted) | O(n) | O(1) |
| Worst Case (Reverse Sorted) | O(n²) | O(1) |
| Average Case | O(n²) | O(1) |
Bubble Sort Step-by-Step
Array: [64, 34, 25, 12, 22, 11, 90]
Pass 1 (i=0):
Compare 64 > 34 ā Swap ā [34, 64, 25, 12, 22, 11, 90]
Compare 64 > 25 ā Swap ā [34, 25, 64, 12, 22, 11, 90]
Compare 64 > 12 ā Swap ā [34, 25, 12, 64, 22, 11, 90]
Compare 64 > 22 ā Swap ā [34, 25, 12, 22, 64, 11, 90]
Compare 64 > 11 ā Swap ā [34, 25, 12, 22, 11, 64, 90]
Compare 64 > 90 ā No swap ā [34, 25, 12, 22, 11, 64, 90]
Result: [34, 25, 12, 22, 11, 64, 90] (90 is sorted)
Pass 2 (i=1):
Compare 34 > 25 ā Swap ā [25, 34, 12, 22, 11, 64, 90]
Compare 34 > 12 ā Swap ā [25, 12, 34, 22, 11, 64, 90]
Compare 34 > 22 ā Swap ā [25, 12, 22, 34, 11, 64, 90]
Compare 34 > 11 ā Swap ā [25, 12, 22, 11, 34, 64, 90]
Compare 34 > 64 ā No swap ā [25, 12, 22, 11, 34, 64, 90]
Result: [25, 12, 22, 11, 34, 64, 90] (34, 64, 90 are sorted)
Final Sorted Array:
[11, 12, 22, 25, 34, 64, 90]
š» Practice Exercise
Challenge 1: Modify the bubble sort program to sort the array in descending order.
Challenge 2: Count the number of swaps performed during the bubble sort.
š Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble Sort for Descending Order
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] < arr[j+1]) { // Change > to < for descending
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\nSorted array in descending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Frequently Asked Questions
1. What is bubble sort in C?
Bubble sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order. The process continues until the list is sorted.
2. What is the time complexity of bubble sort?
Bubble sort has a time complexity of O(n²) in the worst and average cases, and O(n) in the best case (when the array is already sorted).
3. Why is it called bubble sort?
It is called bubble sort because smaller elements "bubble" to the top of the list, similar to bubbles rising to the surface of water.
4. How can bubble sort be optimized?
Bubble sort can be optimized by adding a flag to check if any swaps were made in a pass. If no swaps were made, the array is already sorted and we can exit early.
5. Is bubble sort stable?
Yes, bubble sort is a stable sorting algorithm. It maintains the relative order of equal elements.
š” Tip: Bubble sort is a great starting point for learning sorting algorithms. Once you understand it, you can move on to more efficient algorithms like Quick Sort or Merge Sort.