Write a C Program to implement Bubble,Insertion and Selection sort techniques in a single program.

Program:-

#include<stdio.h>
void print(int a[],int n)
{
 int i;
 printf("Array after sorting:-\n");
 for(i=0;i<n;i++)
 { printf("%d ",a[i]); }
}

void bubble_sort(int a[],int n)
{
 int i,j,t;
 for(i=0;i<n-1;i++)
 { for(j=i+1;j<n;j++)
   { if(a[i]>a[j])
     { t=a[i]; a[i]=a[j]; a[j]=t; }
   }
 }
 print(a,n);
}

void selection_sort(int a[],int n)
{
 int i,j,t,p;
 for(i=0;i<n-1;i++)
 { p=i;
   for(j=i+1;j<n;j++)
   { if(a[j]<a[p])
     { p=j; }
     if(p!=i)
     { t=a[p]; a[p]=a[i]; a[i]=t; }
   }
 }
 print(a,n);
}

void insertion_sort(int a[],int n)
{
 int i,j,t;
 for(i=0;i<n;i++)
 { j=i;
   while(a[j]<a[j-1] && j>=0)
   { t=a[j]; a[j]=a[j-1]; a[j-1]=t; j--; }
 }
 print(a,n);
}

//This program is developed by thezenithcoder.blogspot.com

main()
{
 int array[25],size,i,cho;
 printf("Enter the size of the array:");
 scanf("%d",&size);
 printf("Enter %d elements:",size);
 for(i=0;i<size;i++)
 { scanf("%d",&array[i]); }
 printf("1.BUBBLE SORT\n2.SELECTION SORT\n3.INSERTION SORT\n");
 printf("Enter your choice:"); scanf("%d",&cho);
 switch(cho)
 {
  case 1:bubble_sort(array,size); break;
  case 2:selection_sort(array,size);break;
  default:insertion_sort(array,size);break;
 }
 printf("\nThank you for using this program.\n");
}


Output:-

Enter the size of the array:5
Enter 5 elements:5 4 3 2 1
1.BUBBLE SORT
2.SELECTION SORT
3.INSERTION SORT
Enter your choice:1
Array after sorting:-
1 2 3 4 5
Thank you for using this program.

Enter the size of the array:5
Enter 5 elements:5 4 3 2 1
1.BUBBLE SORT
2.SELECTION SORT
3.INSERTION SORT
Enter your choice:2
Array after sorting:-
1 2 3 4 5
Thank you for using this program.

Enter the size of the array:5
Enter 5 elements:5 4 3 2 1
1.BUBBLE SORT
2.SELECTION SORT
3.INSERTION SORT
Enter your choice:3
Array after sorting:-
1 2 3 4 5
Thank you for using this program.

Post a Comment

0 Comments