Created
April 19, 2014 18:58
-
-
Save sidd-at-git/11093983 to your computer and use it in GitHub Desktop.
Javascript: Insertion Sort
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
| /* | |
| Insertion Sort in a traditional way | |
| Practical Example: Sorting a pack of cards in hand from left to right. | |
| Pick up 2nd card, compare with 1st card. | |
| Pick up 3rd card, compare with 2nd card and 1st card. | |
| And so on... | |
| */ | |
| function insertionSort(arr){ | |
| // arr = [10,43,-4,3,9,65,-35,8] | |
| for (var i = 1; i < arr.length; i++) { | |
| var inHand = arr[i], | |
| temp; | |
| for (var j = i - 1; j >= 0; j--) { | |
| if (inHand < arr[j]) { | |
| temp = arr[j]; | |
| arr[j] = inHand; | |
| arr[j+1] = temp; | |
| }; | |
| }; | |
| // arr[j] = inHand; | |
| }; | |
| return arr; | |
| } | |
| /* | |
| Insertion Sort in a smarter form. | |
| */ | |
| function insertionSortAlt(arr) { | |
| for (var i = 1; i < arr.length; i++) { | |
| var inHand = arr[i]; | |
| for (var j = i; j > 0 && inHand < arr[j-1] ; j--) { | |
| a[j] = a[j - 1]; | |
| }; | |
| a[j] = inHand; | |
| }; | |
| return arr; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment