Google News
logo
C Program to Selection sort
The following example of selection sort implemented in C :
Program :
#include <stdio.h>

void selectionSort(int arr[], int n) {
    int i, j, min_index, temp;
    for (i = 0; i < n-1; i++) {
        // Find the minimum element in unsorted subarray
        min_index = i;
        for (j = i+1; j < n; j++)
            if (arr[j] < arr[min_index])
                min_index = j;

        // Swap the minimum element with the first element
        temp = arr[i];
        arr[i] = arr[min_index];
        arr[min_index] = temp;
    }
}

int main() {
    int arr[] = {15, 32, 81, 4, 46};
    int n = sizeof(arr)/sizeof(arr[0]);
    int i;

    printf("Unsorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);

    selectionSort(arr, n);

    printf("\nSorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
    return 0;
}
Output :
Unsorted array: 15 32 81 4 46 
Sorted array: 4 15 32 46 81 
In this example, the selectionSort function takes an array and its size as parameters, and uses nested loops to find the minimum element in the unsorted subarray, and swap it with the first element of the subarray.

The main function initializes an array, calls selectionSort to sort it, and prints the unsorted and sorted array.