c program on bubble sort.

 what is bubble sort:-  

                                   Bubble sort is a simple sorting algorithm in which we sort the element by repeatedly swap the element if they are in wrong order.

Example:
First Cycle:
6 1 3 2 9 ) –> ( 1  3 2 9 ), Here, in this algorithm we compares the first two elements, and swaps since 6>1.

( 1 6 3 2 9 ) –>  ( 1 3 6 2 9 ), Swap since 6>3
( 1 3 6 2 9 ) –>  ( 1 3 2 6 9 ), Swap since 6 > 2
1 3 2 6 9  ) –> ( 1 3 2 6 9 ), Now, since these elements are already in order (9>6), so algorithm does not swap them.

Second Cycle:
(1 3 2 6 9) –> (1 3 2 6 9 )
1 3 2 6 9 ) –> ( 1 2 3 6 9 ), Swap since 3>2
1 3 2 6 9) –> ( 1 3 2 6 9), 
1 3 2 6 9 ) –>  (1 3 2 6 9 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Cycle:
1 3 6 9 ) –> ( 1 3 2 6 9 )
( 1 3 2 6 9 ) –> ( 1 2 3 6 9)
1 2 3 6 9 ) –> ( 1 2 3 6 9 )
1 2 3 6 9 ) –> ( 1 2 3 6 9 )

And finally we find the sorted array

1 2 3 6 9

Code:-

#include<stdio.h>
int main()
{
int n,a[100],tem,i,j;
printf(“Enter the number of element in the araryn”);
scanf(“%d”,&n);
printf(“Enter the element of the arrayn”);
for(int i=0;i<n;i++)
scanf(“%d”,&a[i]);
// bubble sort
for(i=0;i<n1;i++)
{
for(j=0;j<ni1;j++)
{
if(a[j]>a[j+1])
{
tem=a[j];
a[j]=a[j+1];
a[j+1]=tem;
}
}
}
printf(“The sorted array is:-n”);
for(int i=0;i<n;i++)
printf(“%d “,a[i]);
return 0;
}

Output:-

Enter the number of element in the arary
5
Enter the element of the arary
4 1 6 2 7
The sorted arary is:-
1 2 4 6 7



Leave a Reply

Your email address will not be published.