Skip to content

Instantly share code, notes, and snippets.

@gene-ressler
Last active November 5, 2022 22:43
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 gene-ressler/15fb6800d5453f694c669f1a4473a20d to your computer and use it in GitHub Desktop.
Save gene-ressler/15fb6800d5453f694c669f1a4473a20d to your computer and use it in GitHub Desktop.
Quickselect with some optimizations
#include <stdio.h>
#include <stdlib.h>
static int med3(int a, int b, int c) {
return a < b
? c < a ? a : (c < b ? c : b)
: c > a ? a : (c > b ? c : b);
}
static void swap(int *a, int i, int j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
}
// Quick select with Dutch national flag and median-3 pivot.
int sel(int *a, int n, int r) {
while (n != 1) {
int mid = med3(a[n / 4], a[n / 2], a[3 * n / 4]);
int i = 0, j = 0, k = n - 1;
while (j <= k)
if (a[j] < mid) swap(a, i++, j++);
else if (a[j] > mid) swap(a, j, k--);
else j++;
if (r < i) {
n = i;
} else if (r >= j) {
a += j;
n -= j;
r -= j;
} else {
return a[i];
}
}
return a[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment