
Selection Sort in C
Algorithm
Input: Input the size and elements of an array.
Output: Displays the array in sorted order
- Start
- Read the size of the array say n
- i = 0
- while ( i <n )
4.1 read a [ i ]
4.2 i++ - for i = 0 to n-1
5.1 min_idx=i
5.2 for j = i+1 to n-1
5.2.1 if a[j] < a[min_idx]
5.2.1.1 min_idx = j
5.3 if min_idx != i
5.3.1 temp=a[min_idx]
5.3.2 a[min_idx]=a[i]
5.3.3 a[i]=temp - Print "The sorted array is " a [ n ]
- Stop
C Program
#include<stdio.h>
void main()
{
int n,temp,small;
printf("Enter the size of array:");
scanf("%d",&n);
int a[n];
printf("Enter the elements in the array:\n");
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
}
printf("The array before sorting is:");
for(int i=0;i<n;i++) {
printf("%d\t",a[i]);
}
int i, j, min_idx;
//loop for each pass
for (i = 0; i < n-1; i++) {
min_idx = i;
//loop for finding index of smallest element
for (j = i+1; j < n; j++) {
if (a[j] < a[min_idx]) {
min_idx = j;
}
}
//swapping statements
if(min_idx != i) {
temp=a[min_idx];
a[min_idx]=a[i];
a[i]=temp;
}
}
printf("\nThe array after sorting is:");
for(int i=0;i<n;i++) {
printf("%d\t",a[i]);
}
}
Output
Enter the size of array:5
Enter the elements in the array:
5
9
7
2
1
The array before sorting is:5 9 7 2 1
The array after sorting is:1 2 5 7 9
Comments