C program for Bubble Sort

Today I am going to share how to perform bubble sort in C programming language. What is Bubble Sort? Bubble sort is a very simple sorting algorithm which compares consecutive numbers and swap them if both are not in right order. This gives the biggest element at the end in each inner loop cycle. Here is an animated example for bubble sort:
#include
#include

  void bubbleSort(int arr[],int length)
  {
        int i,j,temp;
         for(i=length;i>0;i--)
         {
            for(j=0;j<=i;j++)
   { 
                if(arr[j]>arr[j+1])
                { 
//swap if previous value is bigger then next value
                    temp=arr[j];
     arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
   }// End of Inner For loop
        }// End of Outer For loop.
  }// End of BubbleSort Function
  


 void main()
 {

  
  int data[] = {4,3,5,2,9,2,1,8,7,0}
  int i;

  clrscr();

  printf("\nData before sorting: ");
  
  for( i=0; i<10; i++)
  { 
   printf("%d , ",data[i]);
  }
       
  bubbleSort(data,10);

  printf("\nData after sorting: ");
  
  for( i=0; i<10; i++)
  {
   printf("%d , ",data[i]);
  }
  
  } //End of this example.

Post a Comment

2 Comments
thnk dude

can u do any other sorting techniches using c
The above is not a full bubble sort, Set a flag to zero. A bubble goes from low to high and back again The sort compares and if necessary exchanges adjacent pairs of entries. Any exchange requires a flag to be set to 1.

if no exchange took place the sort has completed.

When concluding the comparing the last and last-1, on the way up, we know that the last entry is the highest. Now do the comparisons from the top down to zero. Now the zero'th entry has the lowest value, and the last the highest, so begin one up from the bottom to one down from the top. reset the flag and repeat. Anytime a pass is done without a swap is a signal that the sort is done. We are finished.