Last active
November 5, 2022 22:43
-
-
Save gene-ressler/15fb6800d5453f694c669f1a4473a20d to your computer and use it in GitHub Desktop.
Quickselect with some optimizations
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
#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