Intermediate 25 min

Implementation

Let’s code selection sort. It’s straightforward to implement.

Basic Implementation


              function selectionSort(arr) {
const n = arr.length;

for (let i = 0; i < n - 1; i++) {
  let minIndex = i;
  
  // Find minimum in unsorted portion
  for (let j = i + 1; j < n; j++) {
    if (arr[j] < arr[minIndex]) {
      minIndex = j;
    }
  }
  
  // Swap if minimum is not at i
  if (minIndex !== i) {
    [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
  }
}

return arr;
}
            

Try It Yourself

🟨 JavaScript Selection Sort Implementation
📟 Console Output
Run code to see output...

Code Explanation

  1. Outer loop (i): Runs n-1 times

    • After each iteration, one element is in place
  2. Find minimum: Inner loop finds minimum

    • Starts from i+1 (unsorted portion)
    • Updates minIndex when smaller element found
  3. Swap: Places minimum at correct position

    • Only swaps if minimum is not already at i

Edge Cases

  • Empty array: Returns empty array (loops don’t run)
  • Single element: Already sorted, returns as-is
  • Already sorted: Still runs all passes (inefficient)
  • All same values: No swaps needed, but still runs

What’s Next?

Now that you can implement it, let’s analyze its performance and complexity.