Wednesday, February 5, 2014

Bubble Sort

//Bubble Sort
//One of the simplest sorting algorithms, but time consuming.

#include<stdio.h>  
//Standard input/output header
#include<conio.h>
void main()
{
   int i,j,temp,a[10],n;
   clrscr();
   printf("\n Enter the array size");
   scanf("%d",&n);  //Size of array to be sorted.
   printf("\n Enter the array elements to be sorted");
   for(i=0;i<n;i++)
   {
      scanf("%d",&a[i]); 
      // Input array element by element.
   }
   printf("\n The given array is...\n");
   for(i=0;i<n;i++)
   { 
     printf("%d ",a[i]); //print input array
   }
   for(i=0;i<n;i++)
   {
     for(j=0;j<n-i-1;j++)
    {
      if(a[j]>a[j+1]) //if current element is greater than
                            //the next element in the array
     {
       temp=a[j];     //current element in temp
       a[j]=a[j+1];   //next element in current loc.
       a[j+1]=temp; //temp to next location
     }
    }
   }
   printf("\n Sorted array is...\n");
   for(i=0;i<n;i++)
   {
     printf("%d\n",a[i]);  //Display sorted array
   }
   getch();
}



No comments:

Post a Comment