The best case and worst case running time of selection sort are O(n^2). This is because regardless of how the elements are initially arranged, on the i iteration of the main for loop, the algorithm always inspects each of the remaining n-i elements to find the smallest one remaining.
Selection sort is the algorithm which takes minimum number of swaps, and in the best case it takes ZERO (0) swaps, when the input is in the sorted array like 1,2,3,4. But the more pertinent question is what is the worst case of number of swaps in selection sort? And for which input does it occur.
Answer: Worst case of number of swaps is n-1. But it does not occur for the just the oppositely ordered input, rather the oppositely ordered input like 6,5,3,2,1 does not take the worst number of swaps rather it takes n/2 swaps. So what is really the input for which the number of swaps takes N-1 swaps, if you analyse a bit more you’ll see that the worst case occurs for “SINE WAVE KIND OF AN INPUT”. That alternatively increasing and decreasing input.
7 6 8 5 9 4 10 3 - input of eight (8) elements will therefore require 7 swaps
3 6 8 5 9 4 10 7 1)
3 4 8 5 9 6 10 7 2)
3 4 5 8 9 6 10 7 3)
3 4 5 6 9 8 10 7 4)
3 4 5 6 7 8 10 9 5)
3 4 5 6 7 8 9 10 6)
3 4 5 6 7 8 10 9 7)
Hence proved. Now the code of selection sort in C.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,c;
int smallest;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n-1;){
smallest = a[i];
c=i;
for(int j=i+1;j<n;j++){
if(a[j]<=smallest){
smallest = a[j];
c=j;
}
}
if(c!=i){
a[c]=a[i];
a[i]=smallest;
// printf("hello\n"); for counting the number of swaps
}
i++;
}
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}