Bubble Sort Program in C

Written by

studymite

Bubble sort program using C

Bubble sort is a widely used sorting algorithm. In Bubble sort we will compare the adjacent elements and swap them if they are in wrong order.

Bubble sort is the most efficient and stable algorithm, as two equal elements will never be swapped in bubble sort.

Time complexity of Bubble Sort is O(n2)

Space complexity of Bubble Sort is O(1)

Code:

#include<stdio.h>

int main() { int a[25],n,i,j,temp; printf("Enter the size of array: "); scanf("%d",&n); printf("Enter the array elements: ");

for(i=0;i&lt;n;++i)
	scanf("%d",&amp;a[i]);
	
for(i=1;i&lt;n;++i)
	for(j=0;j&lt;(n-i);++j)
		if(a[j]&gt;a[j+1])
		{
			temp=a[j];
			a[j]=a[j+1];
			a[j+1]=temp;
		}
		
printf("Array after Bubble sort: ");
for(i=0;i&lt;n;++i)
	printf("%d ",a[i]);

return 0;

}

Output:

Enter the size of array:  4
Enter the array elements:  1 3 9 7

Array after Bubble sort: 1 3 7 9

Bubble Sort Program in C