Pages

Monday 18 February 2019

Program to illustrate Bubble sort

Program to illustrate Bubble sort

Example to illustrate Bubble sort in ascending order
consider an array a[5]
Data    :    16       15      2        13        6
Array  : a[0]      a[1]    a[2]     a[3]    a[4]


Pass 1:

a[0]=16  15   15   15  15
a[1]=15  16   2     2    2
a[2]=2    2    16   13   13
a[3]=13  13  13   16   6
a[4]=6    6    6     6    16

By the end of this pass 1 the highest number 16 will be in a[4]

Pass 2:
a[0]= 15  2    2     2
a[1]= 2    15  13   13
a[2]= 13  13  15   6
a[3]=  6   6    6    15
a[4]= 16  16  16   16
By the end of this pass 2 the second highest number 15 will be in a[3]

Pass 3:
a[0]= 2    2    2
a[1]= 13  13   6
a[2]= 6    6     13
a[3]= 15  15   15
a[4]= 16  16   16
By the end of this pass 3 the third highest number 13 will be in a[2]

Pass 4:
a[0]=  2   2
a[1]=  6   6
a[2]=  13 13
a[3]=  15  15
a[4]=  16  16
By the end of this pass 4 the fourth highest number 6 will be in a[1]


Ascending order sorting :

 // Program to illustrate Bubble sort in ascending order
#include<stdio.h>
void main()
{
 int i,j,a[20],temp,n;
 printf("\n Enter length of the array: \n");
 scanf("%d",&n);
 printf("\n Enter array elements:\n ");
 for(i=0;i<n;i++)
   scanf("%d",&a[i]);
 printf("\n Array elements before Bubble sort :\n");
 for(i=0;i<n;i++)
   printf("\n Address : %p --> Array : a[%d] --> Data : %d",&a[i],i,a[i]);
 for(i=0;i<n;i++)
  {
   for(j=0;j<n-1;j++)
    {
     if(a[j]>a[j+1])
      {
      temp=a[j];
      a[j]=a[j+1];
      a[j+1]=temp;
      }
    }
  }
 printf("\n Array elements after Bubble sort :\n");
 for(i=0;i<n;i++)
   printf("\n Address : %p --> Array : a[%d] --> Data : %d",&a[i],i,a[i]);
}

output:


Descending order sorting :

// Program to illustrate Bubble sort in descending order
#include<stdio.h>
void main()
{
 int i,j,a[20],temp,n;
 printf("\n Enter length of the array: \n");
 scanf("%d",&n);
 printf("\n Enter array elements:\n ");
 for(i=0;i<n;i++)
   scanf("%d",&a[i]);
 printf("\n\n Array elements before Bubble sort :");
 for(i=0;i<n;i++)
   printf("\n Address : %p --> Array : a[%d] --> Data : %d",&a[i],i,a[i]);
 for(i=0;i<n;i++)
  {
   for(j=0;j<n-1;j++)
    {
     if(a[j]<a[j+1])
      {
      temp=a[j];
      a[j]=a[j+1];
      a[j+1]=temp;
      }
    }
  }
 printf("\n\n Array elements after Bubble sort :");
 for(i=0;i<n;i++)
   printf("\n Address : %p --> Array : a[%d] --> Data : %d",&a[i],i,a[i]);
}

output:


1 comment:

Programs in turboc3 : Files

File Handling in C File Handling concept in C language is used for store a data permanently in computer. Using this concept we can store our...