Pages

Sunday, 5 July 2015

Bubble sort

C program for bubble sort

Coding:

#include<stdio.h>
#include<stdlib.h>
int main()
{
float *a,t;
int i,j,n;
printf("Please enter total number of elements:");
scanf("%d",&n);
a=(float*)malloc(n*sizeof(float));
for(i=0;i<n;i++)
{
printf("Enter element %d:",i+1);
scanf("%f",&a[i]);
}
printf("Elements before sorting:");
for(i=0;i<n;i++)
printf("%f ",a[i]);
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("\nElements after sorting:");
for(i=0;i<n;i++)
printf("%f ",a[i]);
return 0;
}
Output:
Please enter total number of elements:4
Enter element 1:10
Enter element 2:9
Enter element 3:2
Enter element 4:15
Elements before sorting:10.000000 9.000000 2.000000 15.000000
Elements after sorting:2.000000 9.000000 10.000000 15.000000