August 2017
Intermediate to advanced
222 pages
5h 3m
English
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 ...