(C++) CPP Programs - 25
Friday, December 14, 2007
25. Write a C program to read ‘N’ elements by selection sort method using functions
a) To find the position of a minimum elements in an array
b) To swap the contents of two positions.
/* Selection sort*/
#include
#include
#include
void main()
{
int i,n,a[45],pos;
clrscr();
printf("\nEnter how many elements\n");
scanf("%d",&n);
printf("\nEnter the numbers one by one\n");
for(i=0;i < n;i++)
scanf("%d",&a[i]);
printf("\nThe given array is\n");
for(i=0;i < n;i++)
printf("%4d",a[i]);
for(i=0;i < n-1;i++)
{
pos=min_ele(a,n,i);
exchange(a,i,pos);
}
printf("\nArray after sorting\n");
for(i=0;i < n;i++)
printf("%4d",a[i]);
getch();
}
min_ele(int a[ ],int n,int i)
{
int pos,j;
pos=i;
for(j=i+1;j < n;j++)
if(a[pos]>a[j])
pos=j;
return(pos);
}
exchange(int a[ ],int i,int pos)
{
int temp;
temp=a[i];
a[i]=a[pos];
a[pos]=temp;
return;
}
0 comments:
Post a Comment