Selection Sort

DSA · Sorting Algorithms

Theory

Selection sort divides the list into a sorted part on the left and an unsorted part on the right. On each pass it finds the smallest element in the unsorted part and swaps it into the next sorted position. It always performs O(n²) comparisons but at most n-1 swaps, which can matter when writes are expensive.

Why we use it

It is simple and makes the minimum number of swaps among basic sorts.

When to use it

Use it for teaching, very small lists, or when memory writes are costly. It is not stable in its basic form.

How it works

  1. Start: i = 0
  2. Find the minimum in arr[i..n-1]
  3. Swap it with arr[i]
  4. i < n - 1? Yes: i = i + 1, repeat. No: Array is sorted.
  5. Done

Syntax

for i in 0..n-1:
    m = index of min(arr[i..n-1])
    swap arr[i], arr[m]

Time: O(n²) always   Space: O(1)   Not stable

Example

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        m = i
        for j in range(i + 1, n):
            if arr[j] < arr[m]:
                m = j
        arr[i], arr[m] = arr[m], arr[i]
        print("Placed", arr[i], "->", arr)
    return arr

selection_sort([29, 10, 14, 37, 13])

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic