C Program to Implement Bubble Sort in C Programming

January 18, 2025 2 Comments » Hits : 375





Bubble Sort in C : All Passes


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 ?

  1. There are ‘N’ number of Unsorted Elements
  2. Total Number of Iterations = N-1
  3. At the End of First Iteration : Largest Element Will get its Exact Final Position
  4. At the End of 2nd Iteration : 2nd Largest Element Will get its Exact Final Position
  5. .
  6. .
  7. .
  8. .
  9. 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

Visual Explanation :


Incoming search terms:

  • vivek

    thankeww sir…
    but i want all the sorting..
    and also post c++ question

  • Lucila Quear

    Top notch posting. Remember to keep up the superior performance.