AIM:
To write a C program to implement
selection sort
ALGORITHM:
Step 1: Start the program.
Step
2: Selection
sort algorithm starts by comparing first two elements of an array
and swapping if necessary.
Step
3: If you want to sort the elements of array in
ascending order and if the first element
is greater than second then, you need to swap the elements.
Step
4:But,
if the first element is smaller than second, leave the elements as it is. Step
5: Then,
again first element and third element are compared and swapped if
necessary.
Step
6: This
process goes on until first and last element of an array is compared.
This completes the first step of
selection sort.
Step
7:If
there are n elements to be
sorted then, the process mentioned above
should be repeated n-1 times to get required result.
Step
8: Stop the program
PROGRAM
#include<stdio.h>
int main()
{
int s,i,j,temp,a[20];
printf("Enter
total elements: ");
scanf("%d",&s);
printf("Enter %d
elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("After sorting is: ");
for(i=0;i<s;i++)
printf(" %d",a[i]);
return 0;
}
OUTPUT
Enter total elements: 5
Enter 5 elements: 4 5 0 21 7
The array after sorting is: 0 4 5 7 21
RESULT: Thus a C
program is written to implement selection sort and executed
successfully
No comments:
Post a Comment