Thursday, 19 April 2012
Sunday, 1 April 2012
Insertion Sort
#include<stdio.h>
#include<conio.h>
#define max 20
void main()
{
int a[max],i,j,k,n;
clrscr();
printf("Enter the number of elements: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the element %d :", i+1);
scanf("%d",&a[i]);
}
printf("Unsorted Array is : \n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n\n");
/* Insertion Sort */
for(j=1;j<n;j++)
{
k=a[j];
for(i=j-1;i>=0 && k<a[i];i--)
a[i+1]=a[i];
a[i+1]=k;
printf("Pass %d, Element inserted in proper place: %d\n",j,k);
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
}
printf("Sorted list is : ");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
getch();
}
Selection Sort
#include<stdio.h>
#include<conio.h>
#define max 20
void main()
{
int n[max],i,j,k,m,temp,smallest;
clrscr();
printf("Enter the number of elements in the array: ");
scanf("%d",&m);
for(i=0;i<m;i++)
{
printf("Enter the element %d: ",i+1);
scanf("%d",&n[i]);
}
printf("Unsorted array is : \n");
for(i=0;i<m;i++)
printf(" %d ",n[i]);
/* Selection sort */
printf("\n\n");
for(i=0;i<m-1;i++)
{
smallest=i;
for(k=i+1;k<m;k++)
{
if(n[smallest]>n[k])
smallest=k;
}
if(i!=smallest)
{
temp=n[i];
n[i]=n[smallest];
n[smallest]=temp;
}
printf("After pass %d elements are : ",i+1);
for(j=0;j<m;j++)
printf(" %d ",n[j]);
printf("\n\n");
}
printf("Sorted array is: ");
for(i=0;i<m;i++)
printf(" %d ",n[i]);
printf("\n\n");
getch();
}
Subscribe to:
Comments (Atom)