Last active
January 7, 2020 02:02
-
-
Save Giagnus64/2eb3b0fd9d931d6c0eb96368e0e1a1ff to your computer and use it in GitHub Desktop.
Insertion Sort JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function insertionSort(arr){ | |
| let beginningIndex = 0; | |
| let currentIndex = 1; | |
| //while the start of the unsorted portion doesnt not start at the after the end of the array | |
| while(currentIndex < arr.length){ | |
| //while the currentIndex does not reach the end of the sorted section or the array (index of -1) | |
| while(currentIndex > 0){ | |
| //get currentValue(value to be sorted) | |
| currentVal = arr[currentIndex]; | |
| //if it is lesser than the last value, swap the two values, otherwise, break out of the loop | |
| if(currentVal <= arr[currentIndex - 1]){ | |
| swap(arr, currentIndex, currentIndex - 1); | |
| currentIndex--; | |
| } else{ | |
| break; | |
| } | |
| } | |
| //add 1 to beginningIndex to account for newly sorted section | |
| beginningIndex++; | |
| //start sorting from index after beginning | |
| currentIndex = beginningIndex + 1; | |
| } | |
| return arr; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment