DEV Community

Ankit Maheshwari
Ankit Maheshwari

Posted on • Originally published at bitveen.com

Selection Sort Explained Simply — Algorithm, Code & Complexity

Selection Sort's superpower: fewest swaps of any simple sorting algorithm — at most n-1 total. In systems where writes are expensive, this matters.

🧠 The Core Idea

Every pass: scan the unsorted region, find the minimum, swap it to the front.

Analogy: Sorting 30 answer sheets by roll number. Scan all, find Roll No. 1, pull it. Scan remaining, find Roll No. 2. Repeat.

📋 Example: [64, 25, 12, 22, 11]

Pass Min Result
1 11 [11, 25, 12, 22, 64]
2 12 [11, 12, 25, 22, 64]
3 22 [11, 12, 22, 25, 64]
4 25 [11, 12, 22, 25, 64] ✅

5 elements → 4 passes → only 2 actual swaps.

💻 JavaScript

function selectionSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let minIdx = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) minIdx = j;
    }
    if (minIdx !== i) [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
  }
  return arr;
}
Enter fullscreen mode Exit fullscreen mode

⏱ Complexity

Case Time Space Stable Max Swaps
All cases O(n²) O(1) n-1

🆚 vs Bubble Sort

Factor Selection Bubble
Swaps n-1 max ✅ Up to n²/2 ❌
Stable ❌ No ✅ Yes

Part 8 of the Bitveen DSA Series. Originally published at bitveen.com

Top comments (2)

Collapse
 
prachub profile image
PracHub

Interesting breakdown of selection sort's swap efficiency. It's often overlooked because of its O(n²) time complexity, but for systems where writes are costly, it makes sense. The script is straightforward, but in most real-world scenarios, n-1 swaps probably won't outweigh the time cost for larger data sets. I've been using prachub.com for technical rounds, and their coding banks cover these algorithm comparisons well. They helped me see where selection sort actually fits in practical applications.

Collapse
 
bitveen profile image
Ankit Maheshwari

Thanks