C program to sort array using bubble sort algorithm

Sorting data either in ascending or descending order is the important computing application that can be achieved by various ways. In this tutorial, we will learn about c program to sort array using bubble sort algorithm.bubble sort algorithm

C program to sort array using bubble sort algorithm


In this method, smaller values gradually move upward or bubble to the top like an air bubble in water and larger values sink down to the bottom of the array.

In every loop, the successive pairs of the elements are compared and swapped if necessary. If the pair has the same value or is in increasing order, we leave as they are.

If there are n elements to be sorted then bubble sorting make n-1 passes through the array.

Let’s see visually how this works.

working of bubble sort algorithm c

For better understanding of the program, you should have proper knowledge of following c programming topics :

C program to sort array elements using bubble sort method

/* sorting array using bubble sort method */

#include <stdio.h>
#define SIZE 10

int main ()
{
   int data[ SIZE ] = { 3, -2, 7, 10, -5, 22, 1, 27, 25, 30};
   int pass, i, temp;

   printf("Original order of data items:\n");

   //printing data items
   for ( i = 0; i < SIZE; ++i)
   {
      printf("%4d", data[ i ]);
   }

   //bubble sort
   for (pass = 1; pass < SIZE; ++pass) //loop for number of passes
   {
      for (i = 0; i < SIZE - 1; ++i)
      {
         //comparing successive elements and swapping
         if (data[ i ] > data[ i + 1])
         {
            temp = data[ i ];
            data[ i ] = data[ i + 1 ];
            data[ i + 1 ] = temp;
         }
      }
   }

   printf("\nData items in ascending order:\n");
   for (i= 0; i < SIZE; ++i)
   {
      printf("%4d", data[ i ]);
   }
   return 0;
}

[adsense1]
Output
C program to sort array using bubble sort algorithm

Explanation

In the above program, variable temp is used to hold data temporarily for swapping and defined macro SIZE which value is set to 10.

On every iteration of the for loop successive comparison is done and largest value moves at the bottom. The sorting is done by the nested for loops and swapping is performed inside if.

if (data[ i ] > data[ i + 1])
{
    temp = data[ i ];
    data[ i ] = data[ i + 1 ];
    data[ i + 1 ] = temp;
}

Bubble sort algorithm for sorting array is an easy method. However, this becomes slow when there are large data items to be sorted.