BUBBLE SORT
Bubble sort is a comparison-based sorting algorithm that repeatedly steps through an array, compares adjacent elements, and swaps them if they are in the wrong order. Each pass “bubbles” the largest unsorted element to its correct position at the end of the array, so the inner loop only runs up to n-1-i to avoid rechecking already sorted elements. Bubble sort can stop early if no swaps occur during a pass, making it slightly more efficient on nearly sorted data. Despite being simple and easy to understand, bubble sort is generally not used in real-world applications due to its O(n²) time complexity, with more advanced algorithms like quick sort and merge sort preferred for practical sorting tasks.
Selection sort and bubble sort are both elementary sorting algorithms, but they operate differently. In selection sort, for each position in the array, the algorithm searches through all remaining elements to find the smallest one and swaps it into place. This means the inner loop goes all the way to the end of the array—there’s no n-1-i limitation—because each position is directly compared with all elements after it. Bubble sort, on the other hand, repeatedly compares adjacent elements and swaps them if they are out of order, causing the largest elements to “bubble” to the end of the array. Because each pass guarantees that the largest unsorted element is at its correct position, the inner loop runs only up to n-1-i to avoid unnecessary comparisons with already sorted elements. In practice, both algorithms are inefficient for large datasets, but bubble sort can be slightly better with nearly sorted data due to its early-exit optimization, while selection sort performs a predictable number of comparisons. For real-world applications, however, more advanced algorithms like quick sort or merge sort are preferred.
#include <stdio.h>
int main(int argc, char *argv[])
{
int numbers[5] = {0};
int swapped;
int totalSwaps = 0; // track total swaps
// Populate the array with numbers
for(int i = 0; i < 5; i++){
printf("Enter value #%d: ", i + 1);
scanf("%d", &numbers[i]);
}
// Perform bubble sort
for(int i = 0; i < 5 - 1; i++) {
swapped = 0;
for(int j = 0; j < 5 - 1 - i; j++) {
if(numbers[j] > numbers[j + 1]) {
// Swap adjacent elements
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
swapped++;
}
}
totalSwaps += swapped; // accumulate total swaps
// Early exit if no swaps occurred
if(swapped == 0) break;
}
// Display sorted array
printf("Sorted Array: ");
for(int i = 0; i < 5; i++){
printf("%d ", numbers[i]);
}
printf("\nTotal number of swaps: %d\n", totalSwaps);
return 0;
}
Last updated