Arrange the array elements in ACS order using Bubble Sort.
Objective
Write a C program to sort an array in ascending order using Bubble Sort.
Algorithm / Approach
- Initialize an unsorted array.
- Start an outer loop
ifrom 1 to the number of elements. - Start an inner loop
jfrom 0 up tolength - i. - Inside the inner loop, compare adjacent elements:
if(ar[j] > ar[j+1]). - If the left element is larger than the right element, swap them using a
tempvariable. - After all loops finish, the array is sorted.
main.c
#include<stdio.h>
int main(){
int i,j,temp;
int ar[8] = {6,5,3,1,8,7,2,4};
printf("BEFORE SORTING :\n");
for(i=0; i < 8; i++) {
printf("%d ",ar[i]);
}
for(i=1; i<=8; i++) {
for(j=0; j < 8-i; j++) {
if(ar[j]>ar[j+1]) {
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
}
printf("\n\nAFTER SORTING :\n");
for(i=0; i < 8; i++) {
printf("%d ",ar[i]);
}
return 0;
}
Expected Output
BEFORE SORT : 6 5 3 1 8 7 2 4 AFTER SORT : 1 2 3 4 5 6 7 8
Explanation of the Program
- Bubble Sort is the most famous introductory sorting algorithm.
- It works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. This causes the largest unsorted numbers to literally "bubble" up to the very end of the array on every pass.
- Because the largest number reaches its final correct position at the end of every pass, the inner loop can safely shrink its boundary by 1 each time (
length - i).
Complexity
Time Complexity
O(n^2) - Due to the nested loops comparing every element.
Space Complexity
O(1) - Sorting is done "in-place" without extra memory.