Professional Documents
Culture Documents
Selection Sort
Selection Sort
Code in C.
Subscribe
How To Implement Selection Sort in C?
Last updated on Mar 29,2022104.6K Views
edureka
edureka
Copy Link
image not found!
In the previous article we have discussed the implementation of Bubble
Sort in C. This article will brief you on how to implement Selection Sort
in C. Following are the pointers this article will focus on,
Selection Sort in C
Algorithm for Selection Sort
Other ways to implement Selection Sort
Let us get started with it then,
Selection Sort in C
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.
[10,5,2,1]
The first element is 10. The next part we must find the smallest number
from the remaining array. The smallest number from 5 2 and 1 is 1. So,
we replace 10 by 1.
Let us continue with this article on Selection Sort in C and see how the
algorithm works,
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 elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn", 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("%dn", a[i]);
return 0;
}