Sorting Techniques
Sorting Techniques
Sorting Techniques
#include<stdio.h>
void readarray(int a[],int n);
void printarray(int a[],int n);
void bubblesort(int a[],int n);
void insertionsort(int a[],int n);
void selectionsort(int a[],int n);
void shellsort(int a[],int n);
int main()
{
while(1)
{
int ch;
int a[40],n;
printf("\n 1. bubble sort\n 2. insertion sort\n 3. selection sort\n");
printf("\n enter the number of elements ");
scanf("%d",&n);
readarray(a,n);
printf("\n enter the choice");
scanf("%d",&ch);
switch(ch)
{
case 1:bubblesort(a,n);
printarray(a,n);
break;
case 2:insertionsort(a,n);
printarray(a,n);
break;
case 3:selectionsort(a,n);
printarray(a,n);
break;
case 4:shellsort(a,n);
printarray(a,n);
break;
}
}
return 0;
}
void readarray(int a[],int n)
{
printf("\n enter the elements");
for(int i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
}
void printarray(int a[],int n)
{
printf("\n after sorting the elements are:");
for(int i=0;i<=n-1;i++)
{
printf("\t%d",a[i]);
}
}
void bubblesort(int a[],int n)
{
int t;
for(int i=n-1;i>=0;i--)
for(int j=0;j<i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
void insertionsort(int a[],int n)
{
int t;
for(int i=1;i<=n-1;i++)
{
t=a[i];
for(int j=i-1;j>=0;j--)
if(a[j]>t)
{
a[j+1]=a[j];
a[j]=t;
}
}
}
void selectionsort(int a[],int n)
{
for(int i=0;i<=n-1;i++)
{
int min=i;
for(int j=i+1;j<=n-1;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=i)
{
int t=a[min];
a[min]=a[i];
a[i]=t;
}
}
}
void shellsort(int a[],int n)
{
for(int gap=n/2;gap>=1;gap=gap/2)
{
for(int j=gap;j<=n-1;j++)
{
for(int i=j-gap;i>=0;i=i-gap)
{
if(a[i+gap]>a[i])
{
break;
}
else
{
int t=a[i+gap];
a[i+gap]=a[i];
a[i]=t;
}
}
}
}
}