Welcome to our comprehensive guide on C Bubble Sort! This tutorial is designed to help both beginners and intermediates understand the concept of Bubble Sort in the C programming language. Let's dive in!
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
Bubble Sort is easy to understand and implement. It's a good starting point for learning about sorting algorithms. However, it has a disadvantage: it's not the most efficient sorting algorithm, especially for large data sets.
Here's a simple implementation of Bubble Sort in C:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for(int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int size) {
for (int 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]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}Optimized Bubble Sort: The above implementation has a time complexity of O(n^2). An optimized version can be achieved by keeping track of the last swap, and if no swap happens in a pass, the list is sorted. This reduces the time complexity to O(n).
Efficient Bubble Sort: The Efficient Bubble Sort (also known as the modified bubble sort) works by setting a flag, which is initially set to true. If the array is sorted, the flag will be false. In each pass, if no swap occurs, the flag is set to false. The time complexity is O(n^2), but only half of the comparisons occur in the worst case.
What is the time complexity of the standard Bubble Sort?
That's all for today! Stay tuned for more tutorials on C programming. Happy coding! 💻🚀