The selection sort is a sorting algorithm that sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.

Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Selection Sort in Data Structure and Algorithm - DSA - Saral Code

Code

#include<stdio.h>

void swap(int * x, int * y){
    int temp = *x;
    *x = *y;
    *y=temp;
}

void printArray(int arr[], int n){
    for (int i = 0; i < n; i++){
        printf("%d ", arr[i]);
    }
}

void selectionSort(int arr[], int n){
    for (int i = 0; i < n-1; i++){
        int MIN=i;
        for (int j = i+1; j < n; j++){
            if(arr[j]<arr[MIN]){
                MIN=j;
            }
        }
        if(MIN!=i){
            swap(&arr[i], &arr[MIN]);
        }
    }
}

void main(){
    int arr[] = {5,20,4,16,2};
    int n=5;
    // Sorting array
    selectionSort(arr, n);
    // Printing array
    printArray(arr,n);
}