Course contentsShow
← C
Lesson 1048 of 1,21914. Data Structures in CFree lesson

Selection Sort: Finding the minimum

Selection Sort: Finding the minimum

What you'll learn: How to scan an unsorted array to identify the smallest value and move it to its correct position.

The "Smallest First" Strategy

Imagine you are standing in front of a messy row of five numbered cards. You want to sort them from lowest to highest. The simplest way to start is to look at every single card, find the one with the lowest number, and swap it with the card in the very first position.

Selection Sort does exactly this. It treats the array as two parts: a sorted section on the left and an unsorted section on the right. In the beginning, the whole array is unsorted. The algorithm's job is to search the unsorted section for the "minimum" value and "select" it to join the sorted section.

How the Scan Works

To find the minimum, we don't just look at the whole array at once; we compare elements one by one.

  1. We assume the first unsorted element is the smallest (we store its index in a variable).
  2. We look at the next element. Is it smaller than our current minimum?
  3. If yes, we update our "minimum index" to this new position.
  4. We keep going until we hit the end of the array.
  5. Once we are sure we have found the absolute smallest value, we swap it with the element at the start of the unsorted section.

Seeing it in C

Here is how we find the smallest value in an array and bring it to the front:

#include <stdio.h>

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = 5;

    // We start at the first position
    int min_idx = 0;

    // Scan the rest of the array to find the true minimum
    for (int j = 1; j < n; j++) {
        if (arr[j] < arr[min_idx]) {
            min_idx = j; // Found a new smallest value!
        }
    }

    // Swap the found minimum with the first element
    int temp = arr[min_idx];
    arr[min_idx] = arr[0];
    arr[0] = temp;

    printf("The smallest value is now at the front: %d", arr[0]);

    return 0;
}

By the end of this single pass, the number 11 (the smallest in our list) has been moved to index 0. The algorithm would then repeat this process for the second position, then the third, until the entire row is ordered.

Key takeaway

Selection Sort works by repeatedly finding the smallest remaining element and swapping it into its final sorted position.