Data Structures and Algorithms - Old Questions
8. Write a program to sort an array using selection sort.
5 marks
|
Asked in 2071
#include<stdio.h>
int main()
{
int a[10],i,j,temp,min,loc,n;
printf("\\n Enter the max no.of Elements to Sort: \\n");
scanf("%d",&n);
printf("\\n Enter the Elements : \\n");
for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
for (i=0; i<=n-1; i++)
{
min=a[i];
loc=i;
for (j=i+1; j<=n-1; j++)
{
if (a[j]<min)
{
min=a[j];
loc=j;
}
}
if (loc!=i)
{
temp=a[i];
a[i]=a[loc];
a[loc]=temp;
}
}
printf("The sorted array is: \\n");
for(i=0; i<n; i++)
{
printf("%d\\t",a[i]);
}
return 0;
}