don't make quickselect "destructive"; recompile

This commit is contained in:
NunoSempere 2023-12-14 13:02:27 +00:00
parent c3de336a5b
commit 95e4532c2c
23 changed files with 13 additions and 3 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -6,6 +6,7 @@
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memcpy
/* Parallel sampler */
void sampler_parallel(double (*sampler)(uint64_t* seed), double* results, int n_threads, int n_samples)
@ -105,15 +106,24 @@ static int partition(int low, int high, double xs[], int length)
static double quickselect(int k, double xs[], int n)
{
// https://en.wikipedia.org/wiki/Quickselect
double *ys = malloc((size_t)n * sizeof(double));
memcpy(ys, xs, (size_t)n * sizeof(double));
// ^: don't make this operation "destructive"
int low = 0;
int high = n - 1;
for (;;) {
if (low == high) {
return xs[low];
double result = ys[low];
free(ys);
return result;
}
int pivot = partition(low, high, xs, n);
int pivot = partition(low, high, ys, n);
if (pivot == k) {
return xs[pivot];
double result = ys[pivot];
free(ys);
return result;
} else if (k < pivot) {
high = pivot - 1;
} else {

BIN
test/test

Binary file not shown.