32 lines
588 B
C
Raw Permalink Normal View History

#pragma once
2020-10-17 00:43:28 +02:00
// http://ndevilla.free.fr/median/median/index.html
2020-10-17 00:45:08 +02:00
uint32_t getWirthKthSmallest(std::vector<uint32_t> a, uint32_t k)
2020-10-17 00:43:28 +02:00
{
2020-10-17 00:45:08 +02:00
uint32_t l = 0;
uint32_t m = a.size() - 1;
2020-10-17 00:43:28 +02:00
while (l < m) {
2020-10-17 00:45:08 +02:00
uint32_t x = a[k];
uint32_t i = l;
uint32_t j = m;
2020-10-17 00:43:28 +02:00
do {
while (a[i] < x) i++;
while (x < a[j]) j--;
if (i <= j) {
2020-10-17 23:16:42 +02:00
swap(&a[i], &a[j]);
2020-10-17 00:43:28 +02:00
i++;
j--;
}
} while (i <= j);
if (j < k) l = i;
if (k < i) m = j;
}
return a[k];
}