Implementation of bubble sort

January 10th, 2010 by Kevin | Posted under programs.

Bubble sort is probably one of the simplest (the other being insertion sort) sorting algorithms created. The fundamental characteristic in bubble sort is the comparison of two adjacent elements and if they differ then we just swap them. This process is continued till we reach the end of the elements. Then we start from the beginning and again compare the adjacent elements and swap them if necessary. This goes for n iterations, where n is the number of elements to be sorted.

Bubble sort

Bubble sort

The runtime complexity of bubble sort is O(n²) in the worst case. This seems like a put off for using bubble sort and it is just used as a study of sorting algorithms. However practically bubble sort may be used to sort small amounts of data because of it’s simplicity and in place sorting. One example where we might consider using bubble sort is if we need to sort say elements of a dropdown list. However it all depends on the size of the list. If it starts getting large perhaps something like insertion sort which sorts in O(n) time for inserting an element in a presorted list should be considered.

int bubble_sort(int array[], const int size)
{
   int i = 0;
   int j = 0;

   for(j=0; j < size-1; j++)
   {
      for(i=0; i < size-1; i++)
      {
         if(array[i] < array[i+1])
         {
            int tmp = array[i]; array[i] = array[i+1]; array[i+1] = tmp;
         }
      }
   }
   return 0;
}

Simple, isn't it?

 

Related Posts:

Tags:

Do you have any comments on Implementation of bubble sort ?

Spam protection by WP Captcha-Free