#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Selection Sort Algorithm

Selection Sort divides the array into a sorted and an unsorted region. In each iteration, it selects the smallest (or largest) element from the unsorted region and swaps it into its correct position at the boundary of the sorted region.

Algorithm Steps

  • Set the first element as the current minimum.
  • Scan the rest of the array to find the actual minimum element.
  • Swap the minimum found with the first unsorted element.
  • Move the boundary of the sorted region forward by one and repeat.
def selection_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        min_index = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_index]:
                min_index = j
        arr[i], arr[min_index] = arr[min_index], arr[i]
    return arr

print(selection_sort([64, 25, 12, 22, 11]))

Complexity

CaseTimeSpace
Best/Average/WorstO(n²)O(1)

Key Characteristics

  • Not stable by default (equal elements may change relative order).
  • Performs a minimal number of swaps — exactly n-1 in the worst case — useful when write operations are expensive.
  • Simple to implement and understand, making it common in teaching contexts.

Dry Run: Sorting [64, 25, 12, 22, 11] Pass by Pass

Tracing the algorithm by hand is the fastest way to understand it. In each pass, the bold part of the array is already sorted and never touched again.

PassMinimum foundSwapArray after pass
111 (index 4)64 and 11[11, 25, 12, 22, 64]
212 (index 2)25 and 12[11, 12, 25, 22, 64]
322 (index 3)25 and 22[11, 12, 22, 25, 64]
425 (index 3)none needed[11, 12, 22, 25, 64]

After four passes the last element is automatically in place, so an array of n items needs only n − 1 passes. Notice that pass 4 still scanned the remaining items even though nothing moved. Selection sort cannot detect that the data is already sorted, which is why its best case is no better than its worst case.

Counting the comparisons

The first pass compares n − 1 pairs, the second n − 2, and so on down to 1. Adding these gives n(n − 1)/2 comparisons for every input. For 5 items that is 10 comparisons; doubling the input roughly quadruples the work.

The Same Algorithm in Java

public static void selectionSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        if (minIndex != i) {          // skip useless self-swaps
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }
}

The minIndex != i check does not change the time complexity, but it avoids writing an element onto itself, which matters when each write is costly, such as on flash memory.

Why It Is Not Stable, With a Small Example

Take the pairs [(4, "a"), (4, "b"), (1, "c")] sorted by number. The first pass finds 1 and swaps it with the first 4, giving [(1, "c"), (4, "b"), (4, "a")]. The two 4s have changed order, so the sort is unstable. A stable variant exists: instead of swapping, shift elements right and insert the minimum, though this adds extra writes.

Choosing Selection Sort, and Common Slip-Ups

  • Use it for tiny arrays, teaching, or situations where the number of writes must be kept low.
  • Prefer insertion sort when data is nearly sorted, because insertion sort finishes in close to linear time on such input.
  • Prefer merge sort, quick sort or the built-in sort for anything beyond a few dozen items.

Typical mistakes include starting the inner loop at i instead of i + 1, swapping inside the inner loop (which turns it into a slower, bubble-like sort), and comparing against arr[i] instead of the current minimum. Remember the rule: find first, swap once per pass.