Monday, March 12, 2012

Facts about Sorting Techniques

 Bubble sort: comparisons O(n2), Swaps O(n2)  
 Selection Sort: Comparisons O(n2), swaps O(n)  
 Insertion Sort: Comparisons O(n2) , no swaps   
 Insertion sort is best basic sorts.  

Selection Sort example program in C

 /*  
 This is a basic program of Selection sort.  
 Author: Afiz  
 Date:  
 */  
 #include<stdio.h>  
 main()  
 {  
 int a[5]={9,7,4,8,1};// array with 5 elements.  
 int out,in,min,i;// local variable declarations   
 for(out =0;out<4;out++)// outer loop   
      {  
           min =out;   
      for(in=out+1;in<5;in++)// inner loop   
           {  
                if(a[in]<=a[min])  
                     min=in;   
           }  
      int tmp = a[min]; // swap ....   
      a[min]=a[out];  
      a[out]=tmp;  
      }  
 //printing array   
 for(i=0;i<5;i++)  
 {  
      printf("%d\n",a[i]);   
 }  
 }  

Insertion Sort Example program in C

 /*  
 This is a basic program of Insertion sort.  
 Author: Afiz  
 Date:  
 */  
 #include<stdio.h>  
 main()  
 {  
 int a[5]={9,7,4,8,1};// array with 5 elements.  
 int out,in,min,i;// local variable declarations   
 for(out=1;out<5;out++) // outer loop   
      {  
           temp = a[out];  
           in =out;   
      while(in>0 && a[in-1]>=temp) // inner loop   
           {  
                a[in]=a[in-1];  
                --in;   
           }  
           a[in]=temp;   
      }  
 //printing array ..   
 for(i=0;i<5;i++)  
      {  
           printf("%d\n",a[i]); //   
      }  
 }  

Bubble Sort example program in C

 /*  
 This is a basic program of Bubble sort.  
 Author: Afiz  
 Date:  
 */  
 #include<stdio.h>  
 main()  
 {  
 int a[5]={5,5,1,7,-1}; // array with 5 elements.  
 int i,j; // local variable declarations   
 for(i=0;i<5;i++)// outer loop   
 {  
      for(j=1;j<5-i;j++) // outter loop   
           {  
                if(a[j-1]>=a[j])  
                {  
                     int tmp = a[j-1]; // swap   
                     a[j-1]=a[j];  
                     a[j]=tmp;       
                }  
           }  
 }  
 //printing array   
 for(i=0;i<5;i++)  
 {  
      printf("%d\n",a[i]);   
 }  
 }