C Selection Sort

Intermediate
6 min read
Updated: Nov 2026
1 example

Selecting the Minimum

Selection sort divides the array into a sorted prefix and an unsorted rest. Each step selects the minimum of the rest and swaps it into the next position. It always makes O(n^2) comparisons but only at most n - 1 swaps, which helps when writes are expensive. It is not stable in the usual swap form.

Remember
for (i = 0; i < n - 1; i++) {
    min = i;
    for (j = i + 1; j < n; j++) if (a[j] < a[min]) min = j;
    if (min != i) swap(a[i], a[min]);
}

Cheat Sheet

Keep these facts handy while you work with Selection Sort in C.

TopicDetail
Comparisonsn(n-1)/2 always
SwapsAt most n - 1
SpaceO(1)
StableNo (swap form)

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Insertion Sort.

Example 1 — Trace each selection step

Sort 64, 25, 12, 22, 11.

C
#include <stdio.h>

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

    for (int i = 0; i < n - 1; i++) {
        int min = i;
        for (int j = i + 1; j < n; j++)
            if (a[j] < a[min]) min = j;
        if (min != i) { int t = a[i]; a[i] = a[min]; a[min] = t; }

        printf("step %d:", i + 1);
        for (int k = 0; k < n; k++) printf(" %d", a[k]);
        printf("\n");
    }
    return 0;
}

How It Works

  1. Step 1 swaps the minimum 11 with 64.
  2. Step 2 finds 12 and swaps it with 25.
  3. Step 4 finds 25 already in place, so nothing moves.

Edge Cases & Pitfalls

Check these before relying on Selection Sort in real programs.

stable

Unstable swaps

Swapping the minimum to the front can jump over equal keys and reorder them.

always

No best-case speedup

It does the same comparisons even on sorted input.

Key Takeaways

  • Select min, swap into place.
  • Few swaps.
  • Always O(n^2) comparisons.

One line: Selection sort divides the array into a sorted prefix and an unsorted rest.

Frequently Asked Questions

When writes are expensive and you want to minimize swaps; it uses at most n - 1 swaps.
Usually yes because it swaps far less, though both are O(n^2) comparisons.
Continue with "C Insertion Sort" next. Grow a sorted prefix by shifting larger items right. The C Sorting Algorithms hub lists every topic in order.

Next: Insertion Sort

Grow a sorted prefix by shifting larger items right.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful