0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program for Selection Sort Algorithm

Selection sort in JavaScript can be done by looping through the array, finding the smallest element, and swapping it with the current position using code like for (let i = 0; i < arr.length; i++) { let min = i; for (let j = i + 1; j < arr.length; j++) { if (arr[j] < arr[min]) min = j; } [arr[i], arr[min]] = [arr[min], arr[i]]; }.
📋

Examples

Input[5, 3, 8, 4, 2]
Output[2, 3, 4, 5, 8]
Input[1, 2, 3, 4, 5]
Output[1, 2, 3, 4, 5]
Input[]
Output[]
🧠

How to Think About It

To sort an array using selection sort, think of repeatedly picking the smallest number from the unsorted part and putting it at the start. You move through the array, find the smallest value after the current position, then swap it with the current position. This way, the sorted part grows from left to right.
📐

Algorithm

1
Start from the first element of the array.
2
Find the smallest element in the remaining unsorted part of the array.
3
Swap the smallest element found with the element at the current position.
4
Move to the next position and repeat until the whole array is sorted.
💻

Code

javascript
function selectionSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }
  return arr;
}

console.log(selectionSort([5, 3, 8, 4, 2]));
Output
[2, 3, 4, 5, 8]
🔍

Dry Run

Let's trace sorting [5, 3, 8, 4, 2] through selection sort.

1

First pass

Start at index 0 (value 5). Find smallest from index 0 to end: smallest is 2 at index 4. Swap 5 and 2. Array becomes [2, 3, 8, 4, 5].

2

Second pass

At index 1 (value 3). Find smallest from index 1 to end: smallest is 3 at index 1. No swap needed. Array stays [2, 3, 8, 4, 5].

3

Third pass

At index 2 (value 8). Find smallest from index 2 to end: smallest is 4 at index 3. Swap 8 and 4. Array becomes [2, 3, 4, 8, 5].

4

Fourth pass

At index 3 (value 8). Find smallest from index 3 to end: smallest is 5 at index 4. Swap 8 and 5. Array becomes [2, 3, 4, 5, 8].

5

Fifth pass

At index 4 (value 8). Only one element left, no action needed.

PassArray State
1[2, 3, 8, 4, 5]
2[2, 3, 8, 4, 5]
3[2, 3, 4, 8, 5]
4[2, 3, 4, 5, 8]
5[2, 3, 4, 5, 8]
💡

Why This Works

Step 1: Finding the smallest element

The inner loop uses if (arr[j] < arr[minIndex]) to find the smallest value in the unsorted part.

Step 2: Swapping elements

Swapping with [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]] places the smallest element at the current position.

Step 3: Growing the sorted section

Each pass fixes one element in its correct place, so the sorted section grows from left to right.

🔄

Alternative Approaches

Using a helper function to find min index
javascript
function findMinIndex(arr, start) {
  let minIndex = start;
  for (let i = start + 1; i < arr.length; i++) {
    if (arr[i] < arr[minIndex]) minIndex = i;
  }
  return minIndex;
}

function selectionSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = findMinIndex(arr, i);
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }
  return arr;
}

console.log(selectionSort([5, 3, 8, 4, 2]));
This splits logic for clarity but adds function call overhead.
Selection sort with early stop if already sorted
javascript
function selectionSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = i;
    let swapped = false;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
        swapped = true;
      }
    }
    if (!swapped) break;
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }
  return arr;
}

console.log(selectionSort([1, 2, 3, 4, 5]));
Stops early if no smaller element found, saving time on sorted arrays.

Complexity: O(n²) time, O(1) space

Time Complexity

Selection sort uses two nested loops each running up to n times, so it takes O(n²) time even if the array is already sorted.

Space Complexity

It sorts the array in place without extra arrays, so space complexity is O(1).

Which Approach is Fastest?

Selection sort is simple but slower than algorithms like quicksort or mergesort for large data. Early stop optimization helps only on nearly sorted data.

ApproachTimeSpaceBest For
Selection SortO(n²)O(1)Small or nearly sorted arrays
Selection Sort with Early StopO(n²) worst, O(n) bestO(1)Nearly sorted arrays
Quicksort (alternative)O(n log n) averageO(log n)Large unsorted arrays
💡
Always swap elements only after finding the smallest to reduce unnecessary swaps.
⚠️
Beginners often swap elements inside the inner loop instead of after finding the minimum, causing incorrect sorting.