Created
January 8, 2019 23:38
-
-
Save jharris-code/a266666b4d4764c1b71f8e7477aa51f0 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
| let a = [3,1,2,15,4,3,8,8,0]; | |
| let c = 0; | |
| //Time Complexity: O(N^2) | |
| //Space Complexity: O(1) because auxiliary space required (above original data set) is 0. | |
| const insertionSort = (arr) => { | |
| for(let i=0; i < arr.length; i++){ | |
| let j = i; | |
| while(j > 0 && arr[j] < arr[j-1]) { | |
| c += 1; | |
| let temp = arr[j]; | |
| arr[j] = arr[j-1]; | |
| arr[j-1] = temp; | |
| j -= 1; | |
| } | |
| } | |
| return arr; | |
| } | |
| // output: [0,1,2,3,3,4,8,8,15] | |
| console.log(insertionSort(a)); | |
| //output: 15. (Demonstrates time complexity of sorting this particular array) | |
| console.log(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment