Skip to content

Instantly share code, notes, and snippets.

@mvoitko
Created October 11, 2019 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvoitko/dabb028ce94ca5e7d3f2a62de552f836 to your computer and use it in GitHub Desktop.
Save mvoitko/dabb028ce94ca5e7d3f2a62de552f836 to your computer and use it in GitHub Desktop.
Fast version of insertion sort algorithm
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