O'Reilly logo

A Common-Sense Guide to Data Structures and Algorithms by Jay Wengrow

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required