Skip to Content
A Common-Sense Guide to Data Structures and Algorithms
book

A Common-Sense Guide to Data Structures and Algorithms

by Jay Wengrow
August 2017
Intermediate to advanced
222 pages
5h 3m
English
Pragmatic Bookshelf
Content preview from A Common-Sense Guide to Data Structures and Algorithms

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

A Common-Sense Guide to Data Structures and Algorithms, Second Edition, 2nd Edition

Jay Wengrow

Publisher Resources

ISBN: 9781680502794Errata Page