#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubble_sort(int arr[], int n) {
// Loop through n-1 iterations
for (int i = 0; i < n - 1; i++) {
// Flag to track if any swaps occurred
int swapped = 0;
// Compare adjacent elements and swap if needed
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
swapped = 1; // Set flag if a swap occurred
}
}
// If no swaps happened in the inner loop, the array is already sorted
if (!swapped) {
break; // Early termination
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation:
The swap function exchanges the values of two integers pointed to by a and b.
The bubble_sort function takes an array and its size as arguments.
It iterates through the array n-1 times, representing the number of passes needed to sort n elements.
Inside each pass, there's an inner loop that compares adjacent elements.
If the elements are in the wrong order, they are swapped using the swap function.
A flag swapped is used to track if any swaps occurred in the inner loop.
If no swaps happen, it means the array is already sorted, and the loop can be terminated early.
The main function demonstrates how to use the bubble_sort function with an example array.
This code implements the basic bubble sort algorithm, which has a time complexity of O(n^2) in the worst case. Although there are more efficient sorting algorithms, bubble sort remains a simple and intuitive example to understand sorting concepts.
Comments