Skip to content

Instantly share code, notes, and snippets.

@dannas
Created October 4, 2020 19:38
Show Gist options
  • Save dannas/83bd0bfa26504d2b7fe726a5069dc07b to your computer and use it in GitHub Desktop.
Save dannas/83bd0bfa26504d2b7fe726a5069dc07b to your computer and use it in GitHub Desktop.
Bentley insertion sort
#include <stdbool.h>
#include <math.h>
// https://godbolt.org/z/eE853h
void swap(int a[], size_t i, size_t j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
void insertion_sort(int a[], size_t n) {
for (size_t i = 1; i < n; i++) {
for (size_t j = i; j > 0 && a[j-1] > a[j]; j--) {
swap(a, j-1, j);
}
}
}
// Inline swap call
void insertion_sort2(int a[], size_t n) {
for (size_t i = 1; i < n; i++)
for (size_t j = i; j > 0 && a[j-1] > a[j]; j--) {
int t = a[j];
a[j] = a[j-1];
a[j-1] = t;
}
}
// Loop invariant code motion
void insertion_sort3(int a[], size_t n) {
for (size_t i = 1; i < n; i++) {
int t = a[i];
size_t j = i;
for (; j > 0 && a[j-1] > a[j]; j--) {
a[j] = a[j-1];
}
a[j] = t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment