Selection Sort
Selection Sort
Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates
through the array and finds the smallest number in the array and swaps it with the first element
if it is smaller than the first element. Next, it goes on to the second element and so on until all
elements are sorted.
Step 3 – swap the first location with the minimum value in the array
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%d", a[i]);
return 0;
}
Output:
Enter number of elements
4
Enter 4 numbers
4
2
7
1
Sorted Array
1
2
4
7