Bubble Sort in C : All Passes
Bubble Sort Animation : Image from Wikipedia
Program :
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
void bubble_sort(int [],int);
void main()
{
int a[30],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);
getch();
}
//--------------------------------- Function
void bubble_sort(int a[],int n)
{
int i,j,k,temp;
printf("\nUnsorted Data:");
for(k=0;k<n;k++)
printf("%5d",a[k]);
for(i=1;i< n;i++)
{
for(j=0;j< n-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("\nAfter pass %d : ",i);
for(k=0;k< n;k++)
printf("%5d",a[k]);
}
}
What Happens After Each Iteration ?
- There are 'N' number of Unsorted Elements
- Total Number of Iterations = N-1
- At the End of First Iteration : Largest Element Will get its Exact Final Position
- At the End of 2nd Iteration : 2nd Largest Element Will get its Exact Final Position
- .
- .
- .
- .
- At the End of (N-1)th Iteration : (N-1)th Largest Element Will get its Exact Final Position
Output :
Enter no of elements :5 Enter array elements :10 4 55 21 6 Unsorted Data: 10 4 55 21 6 After pass 1 : 4 10 21 6 55 After pass 2 : 4 10 6 21 55 After pass 3 : 4 6 10 21 55 After pass 4 : 4 6 10 21 55




0 Comments:
Post a Comment
Your Feedback :This is Growing Site and Your Feedback is important for Us to improve the Site performance & Quality of Content.Feel Free to contact and Please Provide Name & Contact Email