/*Bubble sort for numbers.Use step count,swap count,comparison count
*/
#include<stdio.h>
void bubble_sort(int a[],int n);
int main()
{
int a[50],n,i;
printf("\nEnter no of elements :");
scanf("%d",&n);
printf("\nEnter array elements :");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
bubble_sort(a,n);
}
void bubble_sort(int a[],int n)
{
int i,j,k,temp,stepcount=0,swapcount=0,compcount=0;
printf("\nUnsorted Data:");
for(k=0;k<n;k++)
printf("%5d",a[k]);
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
compcount++;
stepcount++;
if(a[j]>a[j+1])
{
swapcount++;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
stepcount+=4;
}
}
}
printf("\n No. of steps= %d",stepcount);
printf("\n No. of swaps= %d", swapcount);
printf("\n No. of comparisons= %d",compcount);
printf("\n Sorted Data\n");
for (i=0;i<n;i++)
printf("%5d",a[i]);
}
No comments:
Post a Comment