Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
Suppose we are trying to sort the elements in ascending order.
1. First Iteration (Compare and Swap)
- Starting from the first index, compare the first and the second elements.
- If the first element is greater than the second element, they are swapped.
- Now, compare the second and the third elements. Swap them if they are not in order.
- The above process goes on until the last element.
2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct positions.
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 5
void bubble_sort(int[]);
int main() {
int arr_sort[MAX_SIZE], i;
printf("Simple Bubble Sort Example - Array and Functions\n");
printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_sort[i]);
printf("\nYour Data :");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);
}
bubble_sort(arr_sort);
getch();
}
void bubble_sort(int fn_arr[]) {
int i, j, a, t;
for (i = 1; i < MAX_SIZE; i++) {
for (j = 0; j < MAX_SIZE - 1; j++) {
if (fn_arr[j] > fn_arr[j + 1]) {
//Swapping Values
t = fn_arr[j];
fn_arr[j] = fn_arr[j + 1];
fn_arr[j + 1] = t;
}
}
printf("\nIteration %d : ", i);
for (a = 0; a < MAX_SIZE; a++) {
printf("\t%d", fn_arr[a]);
}
}
printf("\n\nSorted Data :");
for (i = 0; i < MAX_SIZE; i++) {
printf("\t%d", fn_arr[i]);
}
}