Quick Answer

Selection sort finds the smallest item and places it first. It repeats this on the unsorted part of the list. Time is O(n squared) in every case. Space is O(1) because the sort works in place. This post shows 3 approaches. They are basic, swap check and C++. Python and C++ code below was executed.

This algorithm is the first sort many learners meet. It trips up more beginners than it should. Confusion comes from not seeing the array move and not from the idea.

Sections below trace one array by hand and give 3 approaches with tested code. They also compare selection sort vs bubble sort with measured numbers.

What Is Selection Sort?

Selection sort builds a sorted list one item at a time. It splits the array in 2 parts.

Sorted items collect on the left and that part starts empty. Everything else sits in the unsorted part on the right.

Find the smallest value in the unsorted part and move it to the front of that part. Repeat until nothing is left unsorted. Name fits because the sort selects the smallest value every round.

See the sorting algorithms lesson for a short reference.

How Does Selection Sort Work Step by Step?

Take the array [29, 10, 14, 37, 13].

Pass 1 scans every value. Smallest is 10 at index 1. Swapping 10 with the front value 29 gives [10, 29, 14, 37, 13].

Pass 2 ignores index 0 because that spot is done. Smallest of the rest is 13. Swapping 13 with 29 gives [10, 13, 14, 37, 29].

Pass 3 starts at 14. Value 14 is already the smallest so no swap happens. Checks of 37 and 29 still happen.

Pass 4 compares 37 and 29 and swaps them to give [10, 13, 14, 29, 37]. Last value lands correctly on its own.

Sorting these 5 numbers took 10 comparisons and only 3 swaps. Passes made 4 then 3 then 2 then 1 comparisons. Many comparisons and few swaps define this algorithm.

How Do You Code Selection Sort in Python and C++?

Outer loop selects the spot to fill. Inner loop finds the smallest value for that spot.

Approach #1: Basic Python

What you get. Short version. One swap happens per pass outside the inner loop.

def selection_sort(items):
    n = len(items)
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            if items[j] < items[min_index]:
                min_index = j
        items[i], items[min_index] = items[min_index], items[i]
    return items

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

Output is [10, 13, 14, 29, 37].

Approach #2: Swap Check

What you get. Counts of comparisons and swaps. One check avoids swapping an item with its own spot.

items = [29, 10, 14, 37, 13]
comparisons = swaps = 0
for i in range(len(items) - 1):
    min_index = i
    for j in range(i + 1, len(items)):
        comparisons += 1
        if items[j] < items[min_index]:
            min_index = j
    if min_index != i:
        items[i], items[min_index] = items[min_index], items[i]
        swaps += 1
    print("pass", i + 1, items)
print(comparisons, swaps)

Output shows pass 1 [10, 29, 14, 37, 13] then pass 2 [10, 13, 14, 37, 29] then pass 3 [10, 13, 14, 37, 29] then pass 4 [10, 13, 14, 29, 37]. Last line is 10 3 for 10 comparisons and 3 swaps.

Approach #3: C++ Version

What you get. Same logic in C++ with a vector and a main function.

#include <iostream>
#include <utility>
#include <vector>
using namespace std;

void selectionSort(vector<int>& items) {
    int n = items.size();
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (items[j] < items[minIndex]) {
                minIndex = j;
            }
        }
        swap(items[i], items[minIndex]);
    }
}

int main() {
    vector<int> items = {29, 10, 14, 37, 13};
    selectionSort(items);
    for (int value : items) cout << value << " ";
    cout << endl;
}

Output is 10 13 14 29 37.

Tested. Python 3.13.18 matched sorted() on 3,000 random lists. g++ 13.3 compiled the C++ version with warnings on. Tests ran in a cloud sandbox.

What Is the Time and Space Complexity of Selection Sort?

Time is O(n squared) because of 2 nested loops. Every placed item needs a scan of the rest of the list.

Best case matches worst case. Sorted lists still get a full scan on every pass because the sort cannot tell the work is done. Space is O(1) since the sort works inside the original array.

Comparisons follow n times n minus 1 divided by 2. That gives 28 for 8 items and 4,950 for 100 items. Test below used lists of 1,000 items.

List of 1,000 itemsComparisonsSwaps
Sorted499,5000
Reversed499,500500
Random499,500994

Comparisons remain at 499,500 for every order. Swaps never exceed n minus 1 in 3,000 random tests.

When Should You Use Selection Sort?

Use selection sort to learn the find the minimum and place it pattern. Harder algorithms reuse that pattern. For real data use the built in sort.

Test below compared Approach #1 with Python's sorted() on random lists. Table lists the lowest of 3 trials for the Python loop and 5 for sorted() in CPython 3.13.18.

ItemsSelection sortsorted()
1,0000.0112 s0.000062 s
2,0000.0441 s0.000162 s
4,0000.1768 s0.000360 s

Doubling the items made selection sort about 4 times slower. That matches O(n squared). Faster sorts like quick sort and merge sort avoid that growth.

One real edge exists. It makes at most n minus 1 swaps. That matters only when writing data is costly.

Is Selection Sort Stable?

No. Swaps can move an item past an equal item and flip their order. Test below sorts records by the number.

records = [("b", 3), ("a", 3), ("c", 1)]
n = len(records)
for i in range(n - 1):
    min_index = i
    for j in range(i + 1, n):
        if records[j][1] < records[min_index][1]:
            min_index = j
    records[i], records[min_index] = records[min_index], records[i]
print(records)

Output is [('c', 1), ('a', 3), ('b', 3)]. Records b and a both have 3 and they came out as a then b. Use insertion sort or merge sort when stability matters.

How Does Selection Sort vs Bubble Sort Compare?

Bubble sort swaps neighbors again and again and stops early on a sorted list. Selection sort makes 1 swap per pass and never stops early. See the bubble sort walkthrough for the full side by side.

PointSelection sortBubble sort
Swaps on 1,000 random items994244,032
Time on 1,000 random items0.0109 s0.0246 s
Time on 1,000 sorted items0.0103 s0.000031 s
StableNoYes

Bubble sort wins on a sorted list because of its early stop. Selection sort wins when data is out of order. Practice both in the sorting practice set.

Frequently Asked Questions

Is It Stable?

No. Equal values can flip their order during a swap. Insertion sort and merge sort are stable.

Is It Faster Than Bubble Sort?

On 1,000 random items yes. It took 0.0109 s against 0.0246 s. On a sorted list bubble sort with early stop was quicker at 0.000031 s.

Does Input Order Affect the Cost?

No. Comparisons are n times n minus 1 divided by 2 for every order. Only the swap count varies.

Why Does It Make So Few Swaps?

It swaps once per pass after the inner loop finds the smallest value. Most work is comparing and not moving data.

Does Real Code Use It?

Built in sorts do better. Python's sorted() took 0.000062 s for 1,000 items while the loop took 0.0112 s.

Can It Sort Strings?

Yes. Anything that can be compared works. One test sorted pear, fig, apple and kiwi into apple, fig, kiwi, pear.

How Many Comparisons Does It Make?

It makes n times n minus 1 divided by 2. That is 10 for 5 items and 499,500 for 1,000 items.

What Should You Remember About Selection Sort?

Find the smallest and place it. Repeat on what remains.

Key takeaways.

  • Time is O(n squared) for every order and space is O(1).
  • Swaps never exceed n minus 1.
  • Equal items can flip order.

Check yourself. Trace [5, 2, 9, 1, 7]. Which value gets placed first? Answer is 1 and the array becomes [1, 2, 9, 5, 7].