Selection Sort

Selection Sort Algorithm

Key Takeaways: Selection Sort works by repeatedly finding the minimum element from the unsorted part of the array and putting it at the beginning. It is simple to understand but inefficient for large lists.

In the previous tutorial, we learned about Bubble Sort. Now, let's look at another classic algorithm: Selection Sort.

While Bubble Sort swaps adjacent elements constantly, Selection Sort minimizes swaps by searching for the absolute smallest element first.


1. How Does Selection Sort Work?

Selection Sort divides the array into two parts:

  1. The sorted part at the front.
  2. The unsorted part at the back.

Initially, the sorted part is empty, and the unsorted part is the entire array.

The algorithm works like this:

Visual representation of Selection Sort swapping the minimum element to the front

Selection Sort: Scan for the smallest item, then swap it into its correct place.


2. A Step-by-Step Example

Let's sort an array of numbers from lowest to highest: [8, 5, 2, 9, 4]

Pass 1:

Pass 2:

Pass 3:

Pass 4:


3. Selection Sort Code Example

Let's write the Selection Sort algorithm in Python.

Selection Sort in Python

def selection_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n):
        # Find the minimum element in remaining unsorted array
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        # Swap the found minimum element with the first element
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

numbers = [8, 5, 2, 9, 4] print("Original:", numbers) print("Sorted:", selection_sort(numbers))


4. Time Complexity

Time Complexity Calculation

Why is it exactly O(n²)? Let's break down the math:

If we add all those comparisons together: (n-1) + (n-2) + ... + 1. In mathematics, the sum of the first n-1 integers equals n * (n - 1) / 2.

When we use Big O Notation, we ignore constants (like / 2) and smaller terms (like - n), leaving us with the dominant term: O(n²). Because of this, Selection Sort always scans the entire unsorted portion of the array, even if the array is already perfectly sorted!

Graph showing the number of comparisons decreasing each pass in Selection Sort

The number of comparisons decreases linearly, forming a triangle. The total area (total operations) is proportional to n² / 2.

Although it has the same O(n²) time complexity as Bubble Sort, Selection Sort is generally a little bit faster because it performs far fewer memory swaps!


Exercise 1 of 1

?

In Selection Sort, what happens after the algorithm finds the smallest element in the unsorted portion?