#include<stdio.h>
#include<conio.h>
void insertion(int[],int);
void quick(int[],int,int);
int part(int[],int,int);
void bubble(int[],int); /*prototype declaration*/
void selection(int[],int); /* prototype declaration*/
int i,j,temp; /*global variable*/
void main()
{
int a[20],n,choice;
printf("\nEnter the number of elements\t:");
scanf("%d",&n);
if(n>20)
{
printf("\nCould not allocate space!");
getch();
exit(0);
}
for(i=0;i<n;i++)
{
printf("\nEnter number #%d \t:",i+1);
scanf("%d",&a[i]);
}
printf ("\nYou have entered the following element:\n");
for(i=0;i<n;i++) /* printing input array */
printf("\t%d",a[i]);
printf("\n\n\n Select Sorting Technique\t\t");
printf("\n\n\t1. Bubble Sort\n\t2. Selection Sort\n\t3. Quick Sort");
printf("\n\t4. Insertion Sort");
printf("\n\tEnter your choice :");
scanf("%d",&choice);
switch(choice)
{
case 1: bubble(a,n); break; /* calling bubble sort function */
case 2: selection(a,n); break; /* calling selection sort function */
case 3: quick(a,0,n); break; /* calling Quick sort function */
case 4: insertion(a,n); break; /* calling Insertion sort function */
default: printf("\n Wrong choice!");
getch();
exit(0);
}
printf("\nSorted elements in ascending order:\n");
for(i=0;i<n;i++) /* printing sorted array */
printf("\t%d",a[i]);
getch(); }
/* definition of bubble sort*/
void bubble(int a[],int n)
{
for(i=0;i<n-1;i++)
{
for(j=0;j<(n-1)-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
/* definition of selection sort */
void selection(int a[],int n)
{
int loc,min;
for(i=0;i<n;i++)
{
min=a[i];
loc=i;
for(j=i+1;j<n;j++)
{
if(a[j]<min)
{
min=a[j];
loc=j;
}
}
if(loc!=i)
{
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
}
}
/* definition of quick sort */
void quick(int a[],int start, int end)
{
int loc;
if (start<end-1)
{
loc=part(a,start,end);
quick(a,start,loc-1);
quick(a,loc+1,end);
}
}
int part(int a[],int start, int end)
{
int left,right,temp,loc,flag;
loc=left=start;
right=end;
flag=0;
while(flag!=1)
{
while(a[loc]<=a[right] && (loc!=right))
right--;
if(loc==right)
flag=1;
else if(a[loc]>a[right])
{
temp=a[loc];
a[loc]=a[right];
a[right]=temp;
loc=right;
}
if(flag!=1)
{
while((a[loc]>=a[left])&&(loc!=left))
left++;
if(loc==left)
flag=1;
else if(a[loc]<a[left])
{
temp=a[loc];
a[loc]=a[left];
a[left]=temp;
loc=left;
}
}
}
return (loc);
}
/* definition of insertion sort */
void insertion(int a[],int n)
{
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j]) && (j>=0))
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
}
0 Comments