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
- Compare the first two elements.
- If the first element is greater than the second, swap them.
- Move to the next pair and repeat.
- Continue until the end of the array (1 pass complete).
- 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}
Pass | Array State |
---|---|
Pass 1 | 3, 5, 4, 2, 8 |
Pass 2 | 3, 4, 2, 5, 8 |
Pass 3 | 3, 2, 4, 5, 8 |
Pass 4 | 2, 3, 4, 5, 8 |
Time Complexity
Case | Time Complexity |
---|---|
Best Case (Already Sorted) | O(n) |
Average Case | O(n2) |
Worst Case (Reverse Sorted) | O(n2) |
Space Complexity
O(1) โ Bubble sort is an in-place sorting algorithm.