Created
October 11, 2019 21:30
-
-
Save mvoitko/dabb028ce94ca5e7d3f2a62de552f836 to your computer and use it in GitHub Desktop.
Fast version of insertion sort algorithm
This file contains 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
static void insertionSort(int[] a) { | |
for(int i = 1; i < a.length; ++i) { | |
// invariant x[0:i-1] sorted | |
// shift i_th element to its proper place | |
for(int j = i; j > 0 && a[j-1] > a[j]; --j) { | |
swap(a, j-1, j); | |
} | |
} | |
} | |
| |
// faster | |
static void insertionSort(int[] a) { | |
for(int i = 1; i < a.length; ++i) { | |
int j = i; | |
int t = a[j]; | |
while(j > 0 && a[j-1] > t) { | |
a[j] = a[j-1]; | |
--j; | |
} | |
a[j] = t; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment