Selection Sort Algorithm in JavaScript

Today, we’re going to explore another sorting algorithm – the Selection Sort algorithm, implemented in JavaScript.

Selection Sort is another simple sorting algorithm that sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning. Like Bubble Sort algorithm, it’s not the most efficient for large datasets, but it’s a valuable algorithm to understand.

selection sort algorithm
Image from wikipedia
https://en.wikipedia.org/wiki/Selection_sort

Red is current minimum, yellow is sorted list, blue is current item.

Let’s take a look at the JavaScript implementation of Selection Sort algorithm:

function selectionSort(arr) {
  const n = arr.length;
  //outer loop runs on first n-1 elements
  for (let i = 0; i < n - 1; i++) {
    let minIndex = i;

    for (let j = i + 1; j < n; j++) {
      // Find the index of the minimum element
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex != i) {
      // Swap the found minimum element with the first element
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
      //Another way to swap
      //const temp = arr[i];
      //arr[i] = arr[minIndex];
      //arr[minIndex] = temp;
    }
  }

  return arr;
}

// Example usage:
const unsortedArray = [64, 34, 25, 12, 22, 11, 90];
const sortedArray = selectionSort(unsortedArray.slice()); // Create a copy to keep the original array unchanged

console.log("Unsorted Array:", unsortedArray);
console.log("Sorted Array:", sortedArray);

You need to be logged in to view the rest of the content. Please . Not a Member? Join Us

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top