Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 4 · syllabusAsked 1× in KTU papersChecked by code · teacher review pending

Selection sort

Repeatedly select the smallest remaining element and swap it to the front.

Syllabus says: “Sorting Techniques: Selection Sort”

On this page · 19 sections
ormakkurippu ✎
Never-forget card

SELECT the minimum, SWAP it to the front. Always n(n − 1)/2 comparisons, at most n − 1 swaps.

Picture it

Picking the cricket team by height: scan everyone, call the shortest to the front, then scan the rest again.

Write this in the exam

Selection sort repeatedly selects the smallest element of the unsorted part and swaps it with the first unsorted element.

Learning objectives

  • Describe how selection sort builds the sorted part one element per pass.
  • Write the algorithm and trace it pass by pass.
  • Derive its O(n²) comparison count and explain why it is not stable.

Prerequisites

Arrays and indices, nested loops, swapping two variables.

Introduction

Imagine arranging exam papers by roll number: you scan the whole pile for the smallest number, put it first, then scan what remains for the next smallest. Selection sort is exactly that.

Definition

Definition

Selection sort divides the array into a sorted prefix a[0..i−1] and an unsorted suffix a[i..n−1]. In pass i it finds the index of the minimum of the suffix and swaps that element into position i.

How it works

  1. Set min = i (assume the first unsorted element is the smallest).
  2. Compare a[j] with a[min] for every j from i+1 to n−1; whenever a[j] is smaller, set min = j.
  3. Swap a[i] with a[min]. Now a[0..i] holds the i+1 smallest values in order.
  4. Repeat for i = 0 … n−2. The last element is automatically in place.

The number of comparisons does not depend on the input order: pass i always makes n−1−i comparisons.

Where it is used

Useful when writing to memory is expensive (e.g. flash memory), because it performs at most n−1 swaps — fewer than insertion or bubble sort in the worst case.

Worked example

Worked example: 29, 10, 14, 37, 13checked by code
Input29 10 14 37 13
After pass 110 29 14 37 13
After pass 210 13 14 37 29
After pass 310 13 14 37 29
After pass 410 13 14 29 37

Totals: comparisons = 10, swaps = 3

Now watch it run

Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶.

Loading visualizer…

Algorithm

AlgorithmSelection Sort
  1. Step 1:
    Start.
  2. Step 2:
    Read the number of elements n.
  3. Step 3:
    Read the n elements into the array A.
  4. Step 4:
    Repeat Steps 5 to 7 for i = 0 to n-2.
  5. Step 5:
    Set min = i.
  6. Step 6:
    Repeat for j = i+1 to n-1:
    • If A[j] < A[min], set min = j.
  7. Step 7:
    Swap A[i] and A[min] (temp = A[i], A[i] = A[min], A[min] = temp).
  8. Step 8:
    Display the sorted array A.
  9. Step 9:
    Stop.
Pseudocode used by the animated lab · the lines highlighted in the visualizer
Selection sort
  1. 1SelectionSort(a, n)
  2. 2for i ← 0 to n − 2
  3. 3min ← i
  4. 4for j ← i + 1 to n − 1: if a[j] < a[min]
  5. 5min ← j
  6. 6if min ≠ i: swap a[i], a[min]
  7. 7end

C implementation

selection_sort.ctested ✓ 228/228 cases
C
/* Selection Sort — KTU PCCST303, Module 4 (lab-record style) */
#include <stdio.h>

int main()
{
    int a[100], n, i, j, min, temp;

    printf("Enter number of elements: ");
    scanf("%d", &n);
    printf("Enter array elements:\n");
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);

    for (i = 0; i < n - 1; i++) {          /* i = 0 to n-2 */
        min = i;
        for (j = i + 1; j < n; j++)        /* find the smallest in a[i..n-1] */
            if (a[j] < a[min])
                min = j;
        temp = a[i];                       /* swap a[i] and a[min] */
        a[i] = a[min];
        a[min] = temp;
    }

    printf("Sorted array: ");
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}
Sample input / output · KTU PYQ input · real run, compiled with gcc
Enter number of elements: 8
Enter array elements:
45 33 56 22 76 78 40 30
Sorted array: 22 30 33 40 45 56 76 78 

Bold = what you type. Everything else is printed by the program.

Open in the Code Lab →

Complexity

Comparisons = (n−1) + (n−2) + … + 1 = n(n−1)/2

Extra space O(1); in-place.
CaseTimeSwaps
BestO(n²)0
AverageO(n²)≤ n−1
WorstO(n²)n−1

Advantages and disadvantages

AdvantagesDisadvantages
Simple; at most n−1 swapsAlways O(n²) comparisons, even when already sorted
In-place, O(1) memoryNot stable (long-distance swaps can reorder equal keys)

Edge cases

  • n = 0 or 1: the outer loop does not run.
  • Duplicates: [2a, 2b, 1] → first swap gives [1, 2b, 2a] — equal keys change order, which is why it is unstable.
  • Already sorted: still n(n−1)/2 comparisons, zero swaps.

Common mistakes

  • Swapping inside the inner loop every time a smaller element is found (that becomes a different, slower algorithm).
  • Running the outer loop to n−1 instead of n−2 — harmless but shows misunderstanding.
  • Claiming the best case is O(n): there is no early exit.

Asked in KTU exams (1)

Quick check — can you get them all?

Question 1

Q1.Best-case time of selection sort?

Question 2

Q2.Is selection sort stable?

Question 3

Q3.After pass 1 on 29, 10, 14, 37, 13:

Practice

Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.

Exam-ready summary

  • Select minimum of a[i..n−1], swap into a[i].
  • n(n−1)/2 comparisons → O(n²) in all cases; ≤ n−1 swaps.
  • In-place, not stable.

References

  • Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — Ch. 7 (Sorting), Ch. 8 (Hashing)
  • Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — Ch. 2, 6, 7, 8, 11 (Exercise 2.2-2)

Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.

Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)