Selection Sort Implemented

Here’s a JavaScript implementation of Selection Sort:

 function​ selectionSort(array) {
 for​(​var​ i = 0; i < array.length; i++) {
 var​ lowestNumberIndex = i;
 for​(​var​ j = i + 1; j < array.length; j++) {
 if​(array[j] < array[lowestNumberIndex]) {
  lowestNumberIndex = j;
  }
  }
 
 if​(lowestNumberIndex != i) {
 var​ temp = array[i];
  array[i] = array[lowestNumberIndex];
  array[lowestNumberIndex] = temp;
  }
  }
 return​ array;
 }

Let’s break this down. We’ll first present the line of code, followed by its explanation.

 for​(​var​ i = 0; i < array.length; i++) {

Here, we have an outer loop that represents each passthrough of Selection Sort. We then begin keeping track of the index containing ...

Get A Common-Sense Guide to Data Structures and Algorithms now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.