Thursday, June 6, 2013

Sorting - Bubble Sort Tutorial

There are two types of Sorting - Internal and External Sorting.
Internal Sorting refers to sorting in which all the data that is to be sorted should be in memory at a time. External memory refers to sorting in which some data is in the memory and some data should be in auxillary memory like floppy , harddisk ,etc .

One of the Internal Sorting Algorithms is Bubble Sort . 

pseudo code for Bubble sort :

 For I = 0 to N - 2
       For J = 0 to N - 2
         If (A(J) > A(J + 1)
           Temp = A(J)
           A(J) = A(J + 1)
           A(J + 1) = Temp
         End-If
       End-For
     End-For


here is the implementation of Bubble Sort in C .
  

#include <stdio.h>

int main()
{
    int arr[] = {8,7,6,5,4,3,2,1};
    int i,j,t,k;
    
    for (i = 0; i < 7; i++)
    {
        printf("\n Cycle : %d",i);
        for (j = 0; j < 7; j++)
        {
            if (arr[j] > arr[j+1])
            {
                t = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = t ;
                printf("\narr[%d] = %d  , arr[%d] = %d",j,arr[j],j+1,arr[j+1]);
            }
        }
        printf("\n");
        for (k = 0 ; k < 8; k++)
            printf("arr[%d] = %d\t ",k,arr[k]);
        printf("\n");
       
    }
}
 
complexity :

Worst Case : O(n2)
Average Case : O(n2)
Best Case : O(n2)


Tips :

1) For applying bubble sort on n elements , the number of iteration required is (n-1)
2) Each iteration separates out a biggest element from given elements and put it in the end .