C Program to Implement Bubble Sort

C Program to Implement Bubble Sort:
If you are using any software then below program will not give an error, but if you are using TURBO C then you have to make some changes like: void main() and some function like clrscr() or getch().

#include<stdio.h>
#include<conio.h>

void bubble_sort(int[],int);  //Prototyping
main()
{
   int arr[30],num,i;

   printf("Enter no of elements :");
   scanf("%d",&num);

   printf("\nEnter array elements :");
   for(i=0;i<num;i++)
      scanf("%d",&arr[i]);

   bubble_sort(arr,num);
}

void bubble_sort(int aarr[],int num) {
   int i,j,k,temp;

   printf("\nUnsorted Array:");
   for(k=0;k<num;k++)
   {
      printf("%5d",aarr[k]);
   }

   for(i=1;i<num;i++)
    {
      for(j=0;j<num-1;j++)
      {
         if(aarr[j]>aarr[j+1])
         {
            temp = aarr[j];
            aarr[j] = aarr[j+1];
            aarr[j+1] = temp;
         }
      }

      printf("\nPass %d: ",i);
      for(k=0;k<num;k++)
        {
         printf("%5d",aarr[k]);
        }
   }
}

OUTPUT:

Enter no of elements :5

Enter array elements :7 3 1 8 5

Unsorted Array:    7    3    1    8    5
Pass 1:     3    1    7    5    8
Pass 2:     1    3    5    7    8
Pass 3:     1    3    5    7    8
Pass 4:     1    3    5    7    8

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.