Files
c3c/test/unit/stdlib/sort/quickselect.c3
konimarti 5463c398cb Add quickselect (#1654)
* sort: extract partition from quicksort

Extract the partition logic from quicksort into a macro. This allows to
reuse the partition logic for, e.g., the quickselect algorithm.

* sort: implement quickselect

implement Hoare's selection algorithm (quickselect) on the basis of the
already implemented quicksort. Quickselect allows to find the kth
smallest element in a unordered list with an average time complexity of
O(N) (worst case: O(N^2)).

* add quicksort benchmark

Create a top-level benchmarks folder. Add the benchmark implementation
for the quicksort algorithm.

Benchmarks can then be run in the same way as unit tests from the
root folder with:

	c3c compile-benchmarks benchmarks/stdlib/sort
2024-12-03 19:27:26 +01:00

64 lines
779 B
Plaintext

module sort_test @test;
import std::sort;
struct TestCase @local
{
int[] list;
isz k;
int want;
}
fn void! quickselect()
{
TestCase[] tcases = {
{
.list = {3, 4, 1},
.k = 0,
.want = 1,
},
{
.list = {3, 4, 1},
.k = 1,
.want = 3,
},
{
.list = {3, 4, 1},
.k = 2,
.want = 4,
},
{
.list = {3, 2, 4, 1},
.k = 1,
.want = 2,
},
{
.list = {3, 2, 1, 2},
.k = 1,
.want = 2,
},
{
.list = {3, 2, 1, 2},
.k = 2,
.want = 2,
},
{
.list = {3, 2, 1, 2},
.k = 3,
.want = 3,
},
};
foreach (i, tc : tcases)
{
if (try got = sort::quickselect(tc.list, tc.k))
{
assert(got == tc.want, "got: %d, want %d", got, tc.want);
}
else
{
assert(false, "test %d failed", i);
}
}
}