Monday, May 23, 2011

Write a program to sort a user inputted list of integers using Bubble sort. In this method of sorting multiple swapping take place in one pass and required (n-1) power to sort an array of n elements. Smaller elements move to top of list, which is also known as bubble up.


#include
main()
{
int ar[100],i,n;
void bubble(int[],int);
printf(“\n enter size of array”);
scanf(“%d”,&n);
for(i=0;i<=n-1;i++)
{
printf(“\n enter element”);
scanf(“%d”,&ar[i]);
}
printf(“\n elements before sorting”);
for(i=0;i<=n-1;i++)
scanf(“\n%d”,&ar[i]);
bubble(ar,n);
printf(“\n elements after sorting”);
for(i=0;i<=n-1;i++)
scanf(“\n%d”,&ar[i]);
}

void bubble(int ar[],int n)
{
int i,temp,j;
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-2;j++)
{
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}


Output:

enter size of array5
enter element55
enter element33
enter element22
enter element11
enter element44

elements before sorting
55
33
22
11
44
elements after sorting
11
22
33
44
55

No comments:

Post a Comment