Back to Benchmark

Selection Sort - O(n²) Complexity

Understanding why selection sort has quadratic time complexity

What is Selection Sort?

Selection Sort is a simple sorting algorithm that repeatedly finds the minimum (or maximum) element from the unsorted portion and places it at the beginning (or end). The algorithm maintains two subarrays: one sorted and one unsorted.

Key Characteristics:

  • Simple Algorithm: Easy to understand and implement
  • In-Place: Sorts array in place, O(1) extra space
  • Not Stable: May change relative order of equal elements
  • O(n²) Always: Quadratic time complexity regardless of input order
  • Minimal Swaps: Makes at most n-1 swaps (good when writes are expensive)

Think of it like finding the smallest toy in a box, putting it first, then finding the next smallest from the remaining toys, and so on!

How Does Selection Sort Work?

1. Find Minimum in Unsorted Portion

Scan through the unsorted portion of the array to find the minimum element. This requires comparing each element with the current minimum.

2. Swap with First Unsorted Element

Swap the minimum element with the first element of the unsorted portion. This places the minimum in its correct sorted position.

3. Expand Sorted Portion

Move the boundary between sorted and unsorted portions one position to the right. Repeat the process for the remaining unsorted elements.

4. Quadratic Time Complexity

For an array of n elements:

Pass 1: Compare n-1 elements to find minimum
Pass 2: Compare n-2 elements to find minimum
Pass 3: Compare n-3 elements to find minimum
...
Pass n-1: Compare 1 element
Total comparisons: (n-1) + (n-2) + ... + 1 = n(n-1)/2 = O(n²)
Time complexity: O(n²) always
Interactive Selection Sort Visualization
Watch how selection sort finds the minimum and places it in the correct position!

Code Example:

// Selection Sort - O(n²) always
function selectionSort(arr) {
  const n = arr.length;

  // One by one move boundary of unsorted subarray
  for (let i = 0; i < n - 1; i++) {
    // Find minimum element in unsorted array
    let minIndex = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }

    // Swap minimum with first element
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }

  return arr;
}
Built-in Functions for Sorting
Most programming languages provide built-in sorting functions that use efficient algorithms. Selection sort is rarely used directly:

JavaScript/TypeScript

array.sort() - O(n log n) - Efficient sort
// Uses quicksort or similar, NOT selection sort
Selection sort not used - Too slow for production
// Only for educational purposes

Python

sorted(list) - O(n log n) - Timsort
// Uses efficient Timsort, NOT selection sort
Selection sort not used - Educational only
// Too slow for real applications

Java

Arrays.sort() - O(n log n) - Dual-pivot quicksort
// Uses efficient algorithms, NOT selection sort
Selection sort not used - Too inefficient
// Only taught for learning sorting concepts

C++

std::sort() - O(n log n) - Introsort
// Uses efficient hybrid algorithm, NOT selection sort
Selection sort not used - Educational purpose only
// O(n²) is too slow for production code
Why is Selection Sort O(n²)?

1. Nested Loops

Selection sort uses two nested loops:
• Outer loop: n-1 passes (one less than array size)
• Inner loop: compare n-i-1 elements to find minimum in pass i
• Total comparisons: (n-1) + (n-2) + ... + 1 = n(n-1)/2

2. Always Performs Same Work

Unlike insertion sort, selection sort always performs the same number of comparisons regardless of input order:

Best case: O(n²) - Still must scan all unsorted elements
Average case: O(n²) - Same comparisons
Worst case: O(n²) - Same comparisons
No optimization possible - always O(n²)

3. Minimal Swaps Advantage

Selection sort makes at most n-1 swaps (one per pass):

Swaps: O(n) - At most n-1 swaps
Comparisons: O(n²) - Dominates time complexity
Useful when writes are expensive (e.g., flash memory)

⚠️ Why Selection Sort is Rarely Used

Selection sort is simple but always O(n²), even for sorted data. Unlike insertion sort, it doesn't benefit from nearly sorted input. It's mainly used for educational purposes or when writes are extremely expensive.

Time Complexity Comparison
AlgorithmBestAverageWorstSwapsStable
Selection SortO(n²)O(n²)O(n²)O(n)No
Insertion SortO(n)O(n²)O(n²)O(n²)Yes
Bubble SortO(n)O(n²)O(n²)O(n²)Yes
Quick SortO(n log n)O(n log n)O(n²)O(n log n)No
Real-World Examples

💾 Write-Expensive Memory

Selection sort's minimal swaps (O(n)) make it useful when writes to memory are expensive, such as with flash memory or EEPROM where each write operation has a cost. However, this is extremely rare in modern applications.

📚 Educational Purposes

Selection sort is commonly taught in computer science courses because it demonstrates the concept of finding minimum/maximum and the idea of maintaining sorted and unsorted portions. Its simplicity makes it easy to understand.

🎯 Understanding O(n²)

Learning selection sort helps understand why O(n²) algorithms are inefficient. Its consistent O(n²) performance (unlike insertion sort) clearly demonstrates quadratic growth.

🔍 Simple Implementation

When you need a sorting algorithm that's easy to implement from scratch and correctness is more important than performance (e.g., in embedded systems with very small arrays), selection sort might be considered, though insertion sort is usually better.

❌ What NOT to Use It For

Never use selection sort for large arrays or in production code! For any real application, use built-in sort functions (which use O(n log n) algorithms) or implement efficient sorting algorithms. Selection sort is simply too slow.

Key Takeaways
  • ⚠️
    Selection sort is O(n²) - always

    Always performs n(n-1)/2 comparisons regardless of input order - no best case optimization

  • Minimal swaps advantage

    Makes at most n-1 swaps - useful when writes are expensive, though this is rare

  • Not adaptive

    Unlike insertion sort, doesn't benefit from nearly sorted data - always O(n²)

  • Always use O(n log n) algorithms

    For any real application, use quicksort, merge sort, heap sort, or built-in sort functions

Practice Exercises
Test your understanding of selection sort with these exercises. Try to solve them yourself before checking the answers!