Created
May 25, 2019 20:28
-
-
Save mdrmtz/783381f2dff9d3b3497740d8187be2ac to your computer and use it in GitHub Desktop.
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
| /** | |
| i ← 1 | |
| while i < length(A) | |
| j ← i | |
| while j > 0 and A[j-1] > A[j] | |
| swap A[j] and A[j-1] | |
| j ← j - 1 | |
| end while | |
| i ← i + 1 | |
| end while | |
| */ | |
| (function (){ | |
| console.log('Insertion sort'); | |
| let array = [6,5,3,1,8,7,2,4]; | |
| function insertionSortA(array) { | |
| let i = 1; | |
| while(i < array.length) { | |
| let j = i; | |
| while( j > 0 && array[j-1] > array[j]){ | |
| let tmp = array[j-1]; | |
| array[j-1] = array[j]; | |
| array[j] = tmp; | |
| j = j-1; | |
| } | |
| i = i + 1; | |
| } | |
| return array; | |
| } | |
| console.log(insertionSortA(array)); | |
| /** | |
| i ← 1 | |
| while i < length(A) | |
| x ← A[i] | |
| j ← i - 1 | |
| while j >= 0 and A[j] > x | |
| A[j+1] ← A[j] | |
| j ← j - 1 | |
| end while | |
| A[j+1] ← x | |
| i ← i + 1 | |
| end while | |
| */ | |
| function insertionSortB(array) { | |
| let i = 1; | |
| while(i < array.length) { | |
| let x = array[i]; | |
| let j = i - 1; | |
| while( j >= 0 && array[j] > x){ | |
| array[j+1] = array[j]; | |
| j = j - 1; | |
| } | |
| array[j+1] = x; | |
| i = i + 1; | |
| } | |
| return array; | |
| } | |
| console.log(insertionSortB(array)); | |
| /** | |
| function insertionSortR(array A, int n) | |
| if n>0 | |
| insertionSortR(A,n-1) | |
| x ← A[n] | |
| j ← n-1 | |
| while j >= 0 and A[j] > x | |
| A[j+1] ← A[j] | |
| j ← j-1 | |
| end while | |
| A[j+1] ← x | |
| end if | |
| end function | |
| **/ | |
| function insertionSortR(array, n) { | |
| if(n > 0) { | |
| insertionSortR(array,n-1); | |
| let x = array[n]; | |
| let j = n - 1; | |
| while( j >= 0 && array[j] > x){ | |
| array[j+1] = array[j]; | |
| j = j - 1; | |
| } | |
| array[j+1] = x; | |
| } | |
| return array; | |
| } | |
| console.log(insertionSortR(array,array.length-1)); | |
| })(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment