How to perform selection sort, in JavaScript?

How to Perform Selection Sort in JavaScript?

Selection sort is a simple sorting algorithm that sorts an array by repeatedly finding the minimum element from an unsorted part of the array and putting it at the beginning of the sorted part.

The Algorithm

  • Set the first element as the minimum.
  • Compare the minimum element to the second element.
  • If the second element is smaller than the minimum, assign the second element as the new minimum.
  • Repeat step 3 for all the elements in the array.
  • Swap the minimum element with the first element of the unsorted part of the array.
  • Repeat steps 2-5 for all the elements in the array.

The Code

Here is an example of how to perform selection sort in JavaScript:


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;
      }
    }
    if (minIndex !== i) {
      let temp = array[i];
      array[i] = array[minIndex];
      array[minIndex] = temp;
    }
  }
  return array;
}

let unsortedArray = [5, 1, 12, -5, 16, 2, 12, 14];
let sortedArray = selectionSort(unsortedArray);
console.log(sortedArray); // [-5, 1, 2, 5, 12, 12, 14, 16]

In this example, we define a function called selectionSort that takes an array as an argument. The function iterates over each element in the array and swaps the minimum element with the first element of the unsorted part of the array.

We then define an unsorted array and call the selectionSort function on it to obtain a sorted array. Finally, we print the sorted array to the console.

Alternate Implementation

Another way to perform selection sort in JavaScript is by using the reduce method:


function selectionSort(array) {
  return array.reduce((acc, val) => {
    const min = Math.min(...acc);
    acc.splice(acc.indexOf(min), 1);
    return [...acc, min];
  }, []);
}

let unsortedArray = [5, 1, 12, -5, 16, 2, 12, 14];
let sortedArray = selectionSort(unsortedArray);
console.log(sortedArray); // [-5, 1, 2, 5, 12, 12, 14, 16]

In this implementation, we use the reduce method to iterate over each element in the array and build a new array by finding the minimum element and removing it from the original array using splice.

We then define an unsorted array and call the selectionSort function on it to obtain a sorted array. Finally, we print the sorted array to the console.

Both of these implementations are valid ways to perform selection sort in JavaScript. It is up to the developer to choose which one to use based on their needs and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe