HOWTO · JavaScript

Selection Sort in JavaScript

In this article, we will learn the selection sort algorithm in JavaScript. And using this algorithm, we will learn how we can sort array elements in JavaScript with the help of an example.

On this page

Selection sort repeatedly finds the smallest value in the part of an array that is not yet ordered, then puts it at the next position on the left. The selection sort overview introduces the general algorithm; this guide implements it in JavaScript and follows its passes on a concrete array.

What Selection Sort Does

Think of the array as two adjacent regions. The sorted region grows from the left, while the unsorted region occupies the rest. Initially, the sorted region has no items. On each pass, the algorithm scans the unsorted region, remembers the index of its smallest value, and swaps that value with the first item in the region. The sorted region then grows by one position. Once only one item remains outside it, that item is already in the correct position.

The procedure is straightforward:

  1. Treat the current leftmost unsorted index as the position to fill.
  2. Save that index as minIndex, the current best candidate for the smallest value.
  3. Compare each later item with the candidate and update minIndex whenever a smaller value appears.
  4. Swap the candidate with the item at the position to fill.
  5. Move the position one step right and repeat.

The variable stores an index rather than the minimum value itself. That lets the algorithm perform one swap after the scan instead of moving array items every time it finds a smaller candidate.

Implement Selection Sort in JavaScript

This function sorts an array of numbers in place and returns the same array reference. Its outer loop chooses each position to fill. The inner loop starts one place later, so it searches only the unsorted portion. After that scan, a temporary variable preserves the value being swapped.

Run this example in a JavaScript runtime such as Node.js:

function selectionSort(array) {
  for (let i = 0; i < array.length - 1; i++) {
    let minIndex = i;

    for (let j = i + 1; j < array.length; j++) {
      if (array[j] < array[minIndex]) {
        minIndex = j;
      }
    }

    const current = array[i];
    array[i] = array[minIndex];
    array[minIndex] = current;
  }

  return array;
}

const values = [3, 8, 2, 10, 1, 5, 7, 4, 9, 6];
console.log("Input:", values.join(", "));
console.log("Sorted:", selectionSort(values).join(", "));
Input: 3, 8, 2, 10, 1, 5, 7, 4, 9, 6
Sorted: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

The successful run prints the input and then the sorted array. The function changes the input array in place and returns that same array reference, so assign a copy first if you need to retain the original order.

Trace the Algorithm on an Example

For [3, 8, 2, 10, 1, 5, 7, 4, 9, 6], the first scan examines every item and finds 1 at index 4. It swaps that value with the first item, 3. The sorted region now contains 1, and the remaining scan begins at index 1.

On the next pass, the remaining values have 2 as their minimum, so it moves into index 1. The third pass finds 3 and places it at index 2. On the fourth pass, 4 is the minimum of the remaining values and moves to index 3. The fifth pass places 5 at index 4. At every point, the prefix on the left is in ascending order, and the scan never needs to revisit it.

This trace also explains why the code tracks minIndex: during a pass, it may change several times as smaller candidates are found, but the swap happens only after the scan reaches the end of the unsorted region. If the current item is already the minimum, the swap simply exchanges it with itself and the algorithm proceeds.

Time and Space Complexity

For an input of n items, the first pass makes n - 1 comparisons, the next makes n - 2, and the comparisons continue down to one. Their sum is n(n - 1) / 2, so selection sort takes Θ(n²) time in the best, average, and worst cases. It still scans the remaining values when the input is already ordered; the implementation does not detect that it can stop early.

The function uses Θ(1) extra space: it keeps a few indexes and one temporary value, and it modifies the supplied array instead of creating another array proportional to the input size. Selection sort has at most n − 1 exchange passes, but this implementation executes both array assignments on every pass, including a self-swap when minIndex === i. The exchange bound therefore does not mean this code avoids writes when the minimum is already in place. The quadratic comparison count also makes it a poor choice for large collections.

When to Use Selection Sort

Selection sort is useful for learning how an ordering algorithm maintains an invariant: after each pass, the left prefix contains the smallest values in their final order. It is also reasonable for a small array when a simple, in-place implementation matters more than speed. For general application code and larger inputs, prefer JavaScript’s built-in Array.prototype.sort() with a numeric comparator, such as (a, b) => a - b; that method is optimized by the runtime and should be preferred unless a specific requirement calls for this algorithm.

The example compares numbers using <. For strings, objects, or records, the comparison rule must match the values being ordered; this implementation does not accept a custom comparator. To try the code, save it in a JavaScript file and run that file with a JavaScript runtime or paste it into a compatible console.