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<n;++i)
		scanf("%d",&a[i]);
		
	for(i=1;i<n;++i)
		for(j=0;j<(n-i);++j)
			if(a[j]>a[j+1])
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
			}
			
	printf("Array after Bubble sort: ");
	for(i=0;i<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

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019