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);

Now, let’s break down the code. The selectionSort function takes an array as input and performs the Selection Sort algorithm. Initially the whole array is unsorted. The outer loop iterates through the array, and the inner loop finds the index of the minimum element in the unsorted part of the array. This minimum element is then swapped with the first element of the unsorted part.

We create an array called unsortedArray and sort it using selectionSort. The original array remains unchanged due to the use of slice().

There you have it – a simple implementation of the Selection Sort algorithm in JavaScript. Sorting algorithms play a crucial role in computer science, and understanding different approaches enhances your problem-solving skills. If you have any questions, drop them in the comments below. Subscribe for more coding content, and I’ll catch you in the next blog.

Don't Miss Out! Subscribe to Read Our Latest Blogs.

If you found this blog helpful, share it on social media.

Subscription form (#5)

Leave a Comment

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

Pin It on Pinterest

Scroll to Top