From cf60e38b9db07933578e9c76b088284ad2c5281e Mon Sep 17 00:00:00 2001 From: Ahmet Inan Date: Mon, 11 Mar 2024 10:42:28 +0100 Subject: [PATCH] we ain't come this far to omit sorting --- quick_select.hh => quick.hh | 19 ++++++++++++++++++- repeated_median.hh | 2 +- tests/quick_select_test.cc | 2 +- tests/quick_sort_test.cc | 36 ++++++++++++++++++++++++++++++++++++ theil_sen.hh | 2 +- 5 files changed, 57 insertions(+), 4 deletions(-) rename quick_select.hh => quick.hh (81%) create mode 100644 tests/quick_sort_test.cc diff --git a/quick_select.hh b/quick.hh similarity index 81% rename from quick_select.hh rename to quick.hh index e27a5f0..568a4fe 100644 --- a/quick_select.hh +++ b/quick.hh @@ -1,5 +1,5 @@ /* -Quick select algorithm +Quick algorithms for sorting and selecting Copyright 2024 Ahmet Inan */ @@ -57,6 +57,17 @@ static void partition(TYPE *a, int &l, int &h) ++i; } +template +static void sort(TYPE *a, int l, int h) +{ + if (l < h) { + int lt = l, gt = h; + partition(a, lt, gt); + sort(a, l, lt - 1); + sort(a, gt + 1, h); + } +} + template static void select(TYPE *a, int l, int h, int k) { @@ -74,6 +85,12 @@ static void select(TYPE *a, int l, int h, int k) } +template +void quick_sort(TYPE *a, int n) +{ + QUICK::sort(a, 0, n-1); +} + template TYPE quick_select(TYPE *a, int k, int n) { diff --git a/repeated_median.hh b/repeated_median.hh index 6e8944c..4a8612f 100644 --- a/repeated_median.hh +++ b/repeated_median.hh @@ -6,7 +6,7 @@ Copyright 2021 Ahmet Inan #pragma once -#include "quick_select.hh" +#include "quick.hh" namespace DSP { diff --git a/tests/quick_select_test.cc b/tests/quick_select_test.cc index 15795f7..aafaa62 100644 --- a/tests/quick_select_test.cc +++ b/tests/quick_select_test.cc @@ -8,7 +8,7 @@ Copyright 2024 Ahmet Inan #include #include #include -#include "quick_select.hh" +#include "quick.hh" int main() { diff --git a/tests/quick_sort_test.cc b/tests/quick_sort_test.cc new file mode 100644 index 0000000..6e1f93d --- /dev/null +++ b/tests/quick_sort_test.cc @@ -0,0 +1,36 @@ +/* +Test for the Quick sort algorithm + +Copyright 2024 Ahmet Inan +*/ + +#include +#include +#include +#include +#include "quick.hh" + +int main() +{ + const int MAX_N = 1 << 16; + unsigned seed = 42; + if (1) { + std::random_device rd; + seed = rd(); + } + typedef std::default_random_engine generator; + typedef std::uniform_int_distribution distribution; + auto rand = std::bind(distribution(0, MAX_N), generator(seed)); + int a[MAX_N]; + for (int loop = 0; loop < 1000; ++loop) { + int size = rand(); + for (int i = 0; i < size; ++i) + a[i] = rand(); + DSP::quick_sort(a, size); + for (int i = 1; i < size; ++i) + assert(a[i-1] <= a[i]); + } + std::cerr << "Quick sort algorithm test passed!" << std::endl; + return 0; +} + diff --git a/theil_sen.hh b/theil_sen.hh index 5b6055f..4b17f82 100644 --- a/theil_sen.hh +++ b/theil_sen.hh @@ -6,7 +6,7 @@ Copyright 2021 Ahmet Inan #pragma once -#include "quick_select.hh" +#include "quick.hh" namespace DSP {