Back to Home

Selection Sort

An in-place comparison sorting algorithm that repeatedly selects the minimum element and moves it to the sorted part.

Visualization

Step 1 / 16
Speed:

Details

Analogy

Think of arranging a deck of cards by value. You scan the entire deck to find the lowest card (the Ace) and place it at the very beginning. Then, you scan the remaining cards to find the next lowest card (the 2) and place it in the second position. You repeat this until all cards are sorted.

Purpose

To sort an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.

Use Cases

Good for small lists or when memory write operations are a concern, as it minimizes the number of swaps.

Algorithm Steps

Line 1
1
for i = 0 to n-1:
2
minIndex = i
3
for j = i+1 to n:
4
if arr[j] < arr[minIndex]:
5
minIndex = j
6
swap arr[i] with arr[minIndex]
Current
Executed
Pending

Explanation

What's Happening?

Step 1/16

Pass 1: Find the minimum element in the unsorted array [64, 25, 12, 22, 11].

Updates with each step • Clickfor full view

Code Implementation

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr
Selection Sort - Interactive Visualization | AlgoViz | AlgoViz