JS-152-Objects-Arrays
  • Introduction
  • 04-Objects
    • OOP-Basics
      • Overview
      • Coding the Example
    • Prototypes
      • Object Prototypes
      • Prototypes Continued
    • Inheritance
      • Inheritance
    • Synopsis
      • Synopsis
    • Challenges
    • Solutions
      • Constructor Function
        • Person Constructor
        • Explanation
      • Inheritance Challenge
        • Code
        • Explanation
      • Family Challenge
        • Child
        • Pet
  • 05-Arrays
    • Array Basics
      • Array Overview
      • Creating an Array
      • Individual Elements and Length
      • Iterating Over Arrays
    • Array Methods
      • Methods Overview
      • .join() Method
      • .reverse() Method
      • .split() Method
      • .replace() Method
      • .splice() Method
      • .map() Method
      • .indexOf() Method
      • .filter() Method
      • .every() Method
    • Palindrome Algorithm
    • Array Challenges
    • Solutions
      • First and Last
        • First Element
        • Last Element
      • Most Frequent
      • Largest and Smallest
        • Single Array
        • Multiple Arrays
      • Missing Number
      • "Arrays" in the DOM
      • Sorting
        • Bubble Sort
        • Selection Sort
    • Resources
Powered by GitBook
On this page
  • Completed Code
  • Explanation
  • Variables Explanation
  1. 05-Arrays
  2. Solutions
  3. Sorting

Selection Sort

The second sorting method we used is called Selection Sort.

Completed Code

function selectionSort(arr) {
  var minIdx, temp,
    len = arr.length;
  for (var i = 0; i < len; i++) {
    minIdx = i;
    for (var j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIdx]) {
        minIdx = j;
      }
    }
    temp = arr[i];
    arr[i] = arr[minIdx];
    arr[minIdx] = temp;

  }
  return arr;

}
console.log(selectionSort([207, 150, 71, -25, 369, 246, -13, 22, 150]));

Explanation

  1. selectionSort() searches for the element with the lowest value.

  2. The lowest value is -25 with an index of 3.

  3. -25 swaps places with the first element in the array 207. This way we now have the lowest value starting off our array.

  4. Repeat the process, finding the next smallest value and putting it to the right of -25.

  5. Repeat the process until the array is properly sorted.

Variables Explanation

  • minIdx - the index of our smallest value. It is initially set to the first element in our array.

  • temp - a temporary variable to easily allow the value of arr[minIdx] to change.

  • i and j - the indexes of the elements that are being compared.

PreviousBubble SortNextResources

Last updated 7 years ago