Bubble Sort in C

What is Sorting?

Sorting refers to arrange the elements in the array in ascending or descending order.It compares the adjacent elements and shifts the elements accordingly

Complexity: worst and average case is – O(n2)

for example: [10,24,0,5,33,2]——–>[0,2,5,10,24,33]

The code given below refers to bubble sort with sorting in ascending order:

#include
 void main()
 {
     int n,i;
     int a[100];
     printf("enter no. of elements\n");
     scanf("%d",&n);
     printf("enter the elements\n");
     for(i=0;i<n;i++)
     {
         scanf("%d",&a[i]);
     }
     printf("array before sorting:\n");
     displ(a,n);
     sort(a,n);
     printf("array after sorting:\n");
     displ(a,n);
 }
void displ(int a[],int n)
 {
     int i;
     for(i=0;i<n;i++)
     {
         printf("%d ",a[i]);
     }
     printf("\n");
 }
void sort(int a[],int n)
 {
     int i,j,temp;
     for(i=0;ia[j+1])
             {
             temp=a[j];
             a[j]=a[j+1];
             a[j+1]=temp;
             }
         }
     }
 }

OUTPUT:

enter no. of elements
5
enter the elements
12
0
4
1
30
array before sorting:
12 0 4 1 30
array after sorting:
0 1 4 12 30

Leave a Reply