Jay Abhani
Senior Web Development Instructor at almaBetter
Learn how to implement the Bubble Sort in C with step-by-step explanations and code examples. It is ideal for beginners looking to understand this simple sorting algorithm.
Bubble sort is one of the simplest sorting algorithms that work by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items, and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This algorithm is named for the way larger elements "bubble" to the top of the list.
Bubble sort program in C is a straightforward algorithm that repeatedly traverses through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until no more swaps are needed, which means the list is sorted.
// Function to perform bubble sort
function bubbleSort(arr, n)
// Loop through all elements in the array
for i from 0 to n-1
// Loop through the array from the beginning to the end of the unsorted part
for j from 0 to n-i-1
// Compare adjacent elements
if arr[j] > arr[j+1]
// Swap if they are in the wrong order
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
end if
end for
end for
end function
// Function to print an array
function printArray(arr, size)
for i from 0 to size-1
print arr[i] + " "
end for
print newline
end function
// Main function to test the bubble sort algorithm
function main()
arr = [64, 34, 25, 12, 22, 11, 90]
n = length(arr)
// Print the unsorted array
print "Unsorted array:"
printArray(arr, n)
// Sort the array using bubble sort
bubbleSort(arr, n)
// Print the sorted array
print "Sorted array:"
printArray(arr, n)
end function
Bubble Sort Visualisation
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
int i, j, temp;
// Bubble Sort using for loop
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;
}
}
}
printf("Sorted array using for loop: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Uses nested for loops to iterate through the array and perform swaps as necessary.
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
int i = 0, j, temp;
int swapped = 1;
// Bubble Sort using while loop
while (i < n-1 && swapped) {
swapped = 0;
j = 0;
while (j < n-i-1) {
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;
swapped = 1;
}
j++;
}
i++;
}
printf("Sorted array using while loop: \n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Utilizes a while loop with a swapped flag to continue sorting until no swaps are needed, indicating the array is sorted.
#include <stdio.h>
// Function to perform bubble sort
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]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
// Function to print an array
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; 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: \n");
printArray(arr, n);
// Sort the array using bubble sort function
bubbleSort(arr, n);
printf("Sorted array using function: \n");
printArray(arr, n);
return 0;
}
Encapsulates the bubble sort logic within a bubbleSort function and a printArray function for printing the array before and after sorting. The main function calls these to demonstrate sorting.
#include <stdio.h>
void Bubble_sort(int *arr, int n) { //array passed as pointer
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if ( *(arr + j) > *(arr + j + 1)) {
//swapping of array elements using pointers
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
printf("Array after implementing Bubble sort: ");
for (int i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
}
int main() {
int n = 5;
int arr[5] = {100, 400, 200, 500, 300};
Bubble_sort(arr, n);
return 0;
}
In the Bubble_sort function, array elements are compared and swapped using pointer arithmetic (*(arr + j)), ensuring in-place sorting. The sorted array is then printed using pointer dereferencing in a loop. This approach highlights the use of pointers for array operations, making the code more versatile and efficient in memory usage.
#include <stdio.h>
#include <stdbool.h>
int main() {
int n = 5;
int arr[5] = {44, 33, 11, 22, 55};
for (int i = 0; i < n - 1; i++) {
bool flag = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true; //Elements swapped in this pass
}
}
//if flag == false, no swapping is done in this pass
if (flag == false) break; //Array is already sorted, hence break the loop
}
printf("Array after implementing Bubble sort in an optimised way: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Introducing a flag to track if any elements were swapped during each pass. If no swaps occur (flag remains false), the array is already sorted, and the loop breaks early, reducing unnecessary iterations. This optimization improves efficiency for nearly sorted arrays. The final sorted array is then printed.
As we have observed in the above example codes, even if the array is sorted after some passes, it continues to check (n-1) times which is not an optimized way of executing an algorithm.
We can reduce the execution time by optimizing the algorithm so that it will have best-case time complexity of O(n) when the array is sorted.
Best Case Time Complexity: O(n) - Occurs when the array is already sorted; requires one pass with no swaps.
Average and Worst Case Time Complexity: O(n2)O(n^2)O(n2): Due to quadratic growth in comparisons and swaps as the array size increases, typical in random or reverse-ordered arrays.
Space Complexity: O(1) - Bubble sort is an in-place algorithm, requiring only a constant amount of additional memory for temporary variables.
Learn more about C programming language from our latest blog “History of C Language”
Bubble sort in C is an excellent way to get started with learning sorting algorithms due to its simplicity and ease of implementation. While it may not be the most efficient for large datasets, it is a valuable educational tool for understanding the basic principles of sorting.
With the provided code and explanation, you should now have a solid understanding of how to implement and work with bubble sort in C.
For those looking to advance their skills beyond basic algorithms, consider enrolling in AlmaBetter's full stack developer course with the pay after placement opportunity. This can provide a comprehensive learning experience, ensuring you gain expertise in a wide range of technologies and secure a job before having to pay for your education.
Related Articles
Top Tutorials