Skip to content

Selection sort JavaScript algorithm

  • by

The selection sort algorithm in JavaScript involves iteratively finding the minimum element from the unsorted portion of an array and swapping it with the first unsorted element. This process is repeated until the entire array is sorted in ascending order.

The algorithm’s implementation includes nested loops for comparing and swapping elements, resulting in a sorted array at the end.

Here’s a step-by-step explanation of the selection sort algorithm in JavaScript:

  1. Start with an unsorted array of elements.
  2. Iterate through the array from the first element to the second-to-last element. This will be done using a variable i that represents the current index.
  3. Assume the element at index i is the minimum value. Assign i to a variable minIndex.
  4. Start another iteration from the next element after i to the last element of the array. This will be done using a variable j that represents the current index.
  5. Compare the element at index j with the element at index minIndex. If the element at index j is smaller than the element at index minIndex, update minIndex to j.
  6. After the inner loop completes, swap the element at index i with the element at index minIndex. This places the minimum value in its correct position at the beginning of the unsorted part of the array.
  7. Repeat steps 3 to 6 for each subsequent index i, until the second-to-last element of the array.
  8. Once the outer loop completes, the array is sorted in ascending order.

Selection sort JavaScript example

Simple example code implementation of the selection sort algorithm in JavaScript:

function selectionSort(arr) {
  const len = arr.length;
  
  for (let i = 0; i < len - 1; i++) {
    let minIndex = i;
    
    // Find the index of the minimum element in the unsorted part of the array
    for (let j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    
    // Swap the minimum element with the first element in the unsorted part of the array
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }
  
  return arr;
}

// Example usage:
const array = [64, 25, 12, 22, 11];
console.log(selectionSort(array)); 

Output:

Selection sort JavaScript algorithm

You can test the code with different arrays by changing the values in the array variable and calling selectionSort(array).

The time complexity of the selection sort algorithm in JavaScript is O(n^2), where n is the number of elements in the array.

Comment if you have any doubts or suggestions on this JS sorting algorithm topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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