C Program for Selection Sort?

The selection sort is a simple sorting algorithm that works by finding the smallest element from the unsorted portion of the array and placing it at the beginning. This process is repeated until the entire array is sorted.

Syntax

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int minIndex = i;
        for (int j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex])
                minIndex = j;
        }
        // Swap elements
        int temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }
}

How Selection Sort Works

Let's understand the algorithm with an array {20, 12, 23, 55, 21} −

  1. Find minimum: Compare all elements and find the smallest (12)
  2. Swap: Place the minimum at the first position
  3. Repeat: Continue with the remaining unsorted portion
Selection Sort Process Initial: 20 12 23 55 21 After 1: 12 20 23 55 21 Final: 12 20 21 23 55 Minimum found Sorted position

Example

Here's a complete C program implementing selection sort −

#include <stdio.h>

void selectionSort(int arr[], int n) {
    int i, j, minIndex, temp;
    
    for (i = 0; i < n-1; i++) {
        minIndex = i;
        
        // Find minimum element in remaining array
        for (j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        
        // Swap minimum element with first element
        if (minIndex != i) {
            temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

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

int main() {
    int arr[] = {6, 12, 0, 18, 11, 99, 55, 45, 34, 2};
    int n = 10;
    
    printf("Original array: ");
    printArray(arr, n);
    
    selectionSort(arr, n);
    
    printf("Sorted array: ");
    printArray(arr, n);
    
    return 0;
}
Original array: 6 12 0 18 11 99 55 45 34 2 
Sorted array: 0 2 6 11 12 18 34 45 55 99 

Time Complexity

Case Time Complexity Space Complexity
Best Case O(n²) O(1)
Average Case O(n²) O(1)
Worst Case O(n²) O(1)

Conclusion

Selection sort is simple to understand but inefficient for large datasets with O(n²) time complexity. It performs well on small arrays and requires only O(1) extra memory space.

Updated on: 2026-03-15T11:32:54+05:30

105K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements