{"id":13645092,"url":"https://github.com/danlark1/miniselect","last_synced_at":"2025-04-21T13:31:41.944Z","repository":{"id":38224551,"uuid":"311077491","full_name":"danlark1/miniselect","owner":"danlark1","description":"Selection and partial sorting algorithms","archived":false,"fork":false,"pushed_at":"2025-04-03T04:59:16.000Z","size":671,"stargazers_count":136,"open_issues_count":0,"forks_count":8,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-04-03T05:28:37.175Z","etag":null,"topics":["cxx","cxx11","partial-sort","partial-sorting-algorithms","selection-algorithms","sorting-algorithms"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsl-1.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danlark1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE_1_0.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-08T14:12:42.000Z","updated_at":"2025-04-03T04:59:26.000Z","dependencies_parsed_at":"2024-01-14T09:34:15.363Z","dependency_job_id":"3f75501a-a227-47a5-b83f-c7fb0b8ba511","html_url":"https://github.com/danlark1/miniselect","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danlark1%2Fminiselect","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danlark1%2Fminiselect/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danlark1%2Fminiselect/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danlark1%2Fminiselect/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danlark1","download_url":"https://codeload.github.com/danlark1/miniselect/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250064679,"owners_count":21368948,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cxx","cxx11","partial-sort","partial-sorting-algorithms","selection-algorithms","sorting-algorithms"],"created_at":"2024-08-02T01:02:26.674Z","updated_at":"2025-04-21T13:31:41.631Z","avatar_url":"https://github.com/danlark1.png","language":"C++","funding_links":[],"categories":["C++"],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.com/danlark1/miniselect.svg?branch=main)](https://travis-ci.com/danlark1/miniselect)\n[![License](https://img.shields.io/badge/License-Boost%201.0-lightblue.svg)](https://www.boost.org/LICENSE_1_0.txt)\n\nminiselect: Generic selection and partial ordering algorithms\n==============================================================\n\n`miniselect` is a C++ header-only library that contains various generic selection\nand partial sorting algorithms with the ease of use, testing, advice on usage and\nbenchmarking.\n\nSorting is everywhere and there are many outstanding sorting algorithms that\ncompete in speed, comparison count and cache friendliness. However, selection\nalgorithms are always a bit outside of the competition scope, they are\npretty important, for example, in databases ORDER BY LIMIT N is used extremely\noften which can benefit from more optimal selection and partial sorting\nalgorithms. This library tries to solve this problem with Modern C++.\n\n* **Easy:** First-class, easy to use dependency and carefully documented APIs and algorithm properties.\n* **Fast:** We do care about speed of the algorithms and provide reasonable implementations.\n* **Standard compliant:** We provide C++11 compatible APIs that are compliant to the standard [`std::nth_element`](https://en.cppreference.com/w/cpp/algorithm/nth_element) and [`std::partial_sort`](https://en.cppreference.com/w/cpp/algorithm/partial_sort) functions including custom comparators and order guarantees. Just replace the names of the functions in your project and it should work!\n* **Well tested:** We test all algorithms with a unified framework, under sanitizers and fuzzing.\n* **Benchmarked:** We gather benchmarks for all implementations to better understand good and bad spots.\n\nTable of Contents\n-----------------\n\n* [Quick Start](#quick-start)\n* [Testing](#testing)\n* [Documentation](#documentation)\n* [Performance results](#performance-results)\n* [Real-world usage](#real-world-usage)\n* [Contributing](#contributing)\n* [Motivation](#motivation)\n* [License](#license)\n\nQuick Start\n-----------\n\nYou can either include this project as a cmake dependency and then use the\nheaders that are provided in the [include](./include) folder or just pass the\n[include](./include) folder to your compiler.\n\n```cpp\n#include \u003ciostream\u003e\n#include \u003cvector\u003e\n\n#include \"miniselect/median_of_ninthers.h\"\n\nint main() {\n  std::vector\u003cint\u003e v = {1, 8, 4, 3, 2, 9, 0, 7, 6, 5};\n  miniselect::median_of_ninthers_select(v.begin(), v.begin() + 5, v.end());\n  for (const int i : v) {\n    std::cout \u003c\u003c i \u003c\u003c ' ';\n  }\n  return 0;\n}\n// Compile it `clang++/g++ -I$DIRECTORY/miniselect/include/ example.cpp -std=c++11 -O3 -o example\n// Possible output: 0 1 4 3 2 5 8 7 6 9\n//                            ^ on the right place\n```\n\nExamples can be found in [examples](./examples).\n\nWe support all compilers starting from GCC 7 and Clang 6. We are also planning\nto support Windows, for now it is best effort but no issues are known so far.\n\nMore on which algorithms are available, see [documentation](#documentation).\nFor overview of this work you can read the [article](https://danlark.org/2020/11/11/miniselect-practical-and-generic-selection-algorithms/)\nin the author's blog.\n\nTesting\n-------\n\nTo test and benchmark, we use [Google benchmark](https://github.com/google/benchmark) library.\nSimply do in the root directory:\n\n```console\n# Check out the libraries.\n$ git clone https://github.com/google/benchmark.git\n$ git clone https://github.com/google/googletest.git\n$ mkdir build \u0026\u0026 cd build\n$ cmake -DMINISELECT_TESTING=on -DBENCHMARK_ENABLE_GTEST_TESTS=off -DBENCHMARK_ENABLE_TESTING=off ..\n$ make -j\n$ ctest -j4 --output-on-failure\n```\n\nIt will create two tests and two benchmarks `test_sort`, `test_select`,\n`benchmark_sort`, `benchmark_select`. Use them to validate or contribute. You\ncan also use `ctest`.\n\nDocumentation\n-------------\n\nThere are several selection algorithms available, further $n$ is the number\nof elements in the array, $k$ is the selection element that is needed to be found (all algorithms are deterministic and not stable unless otherwise is specified):\n\n\n| Name                      | Average                                                                                                   | Best Case                                                                                                 | Worst Case                                                                                                                | Comparisons                                                                                                                                                                                                                                                                                                                               | Memory                                                                                                                            |\n|-------------------------  |---------------------------------------------------------------------------------------------------------  |---------------------------------------------------------------------------------------------------------  |-----------------------------------------------------------------------------------------------------------------------    |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   |---------------------------------------------------------------------------------------------------------------------------------  |\n| [pdqselect](./include/miniselect/pdqselect.h)                 | $O(n)$   | $O(n)$   | $`O(n\\log n)`$     | At least $2n$. Random data $2.5n$                                                                                                          | $O(1)$                           |\n| [Floyd-Rivest](./include/miniselect/floyd_rivest_select.h)               | $O(n)$   | $O(n)$   | $O(n^2)$           | Avg: $n + \\min(k, n - k) + O(\\sqrt{n \\log n})$                                                                                                                              | $`O(\\log\\log n)`$  |\n| [Median Of Medians](./include/miniselect/median_of_medians.h)           | $O(n)$   | $O(n)$   | $O(n)$                   | Between $2n$ and $22n$. Random data  $2.5n$    | $O(\\log n)$               |\n| [Median Of Ninthers](./include/miniselect/median_of_ninthers.h)          | $O(n)$   | $O(n)$   | $O(n)$                   | Between $2n$ and $21n$. Random data $2n$       | $O(\\log n)$              |\n| [Median Of 3 Random](./include/miniselect/median_of_3_random.h)          | $O(n)$   | $O(n)$   | $O(n^2)$           | At least $2n$. Random data $3n$       | $O(\\log n)$              |\n| [HeapSelect](./include/miniselect/heap_select.h)          | $`O(n\\log k)`$   | $O(n)$   | $`O(n\\log k)`$           | $n\\log k$ on average, for some data patterns might be better       | $O(1)$              |\n| [libstdc++ (introselect)](https://github.com/gcc-mirror/gcc/blob/e0af865ab9d9d5b6b3ac7fdde26cf9bbf635b6b4/libstdc%2B%2B-v3/include/bits/stl_algo.h#L4748)   | $O(n)$   | $O(n)$   | $`O(n\\log n)`$     | At least $2n$. Random data $3n$                                                                                                              | $O(1)$                             |\n| [libc++ (median of 3)](https://github.com/llvm/llvm-project/blob/3ed89b51da38f081fedb57727076262abb81d149/libcxx/include/algorithm#L5159)     | $O(n)$   | $O(n)$   | $O(n^2)$           | At least $2n$. Random data $3n$                                                                                                              | $O(1)$                           |\n\nFor sorting the situation is similar except every line adds $O(k\\log k)$ comparisons and pdqselect is using $O(\\log n)$ memory.\n\n## API\n\nAll functions end either in `select`, either in `partial_sort` and\ntheir behavior is exactly the same as for\n[`std::nth_element`](https://en.cppreference.com/w/cpp/algorithm/nth_element)\nand [`std::partial_sort`](https://en.cppreference.com/w/cpp/algorithm/partial_sort)\nrespectively, i.e. they accept 3 arguments as `first`, `middle`, `end` iterators\nand an optional comparator. Several notes:\n\n* You should not throw exceptions from `Compare` function. Standard library\nalso does not specify the behavior in that matter.\n* We don't support ParallelSTL for now.\n* C++20 constexpr specifiers might be added but currently we don't have them\nbecause of some floating point math in several algorithms.\n* All functions are in the `miniselect` namespace. See the example for that.\n\n- pdqselect\n  - This algorithm is based on [`pdqsort`](https://github.com/orlp/pdqsort) which is acknowledged as one of the fastest generic sort algorithms.\n  - **Location:** [`miniselect/pdqselect.h`](./include/miniselect/pdqselect.h).\n  - **Functions:** `pdqselect`, `pdqselect_branchless`, `pdqpartial_sort`, `pdqpartial_sort_branchless`. Branchless version uses branchless partition algorithm provided by [`pdqsort`](https://github.com/orlp/pdqsort). Use it if your comparison function is branchless, it might give performance for very big ranges.\n  - **Performance advice:** Use it when you need to sort a big chunk so that $k$ is close to $n$.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/TXIm9rTmbmox5ceSyP/giphy.gif\" /\u003e\u003c/p\u003e\n\n- Floyd-Rivest\n  - This algorithm is based on [Floyd-Rivest algorithm](https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm).\n  - **Location:** [`miniselect/floyd_rivest_select.h`](./include/miniselect/floyd_rivest_select.h).\n  - **Functions:** `floyd_rivest_select`, `floyd_rivest_partial_sort`.\n  - **Performance advice:** Given that this algorithm performs as one of the best on average case in terms of comparisons and speed, we highly advise to\n  at least try this in your project. Especially it is good for small $k$ or types that are expensive to compare (for example, strings). But even for median the benchmarks show it outperforms others. It is not easy for this algorithm to build a reasonable worst case but one of examples when this algorithm does not perform well is when there are lots of similar values of linear size (random01 dataset showed some moderate penalties).\n\nWe present here two gifs, for median and for $k = n/10$ order statistic.\n\n\u003cp float=\"left\"\u003e\n  \u003cimg src=\"https://media.giphy.com/media/a5ORb22iMCE0a6D2cf/giphy.gif\" width=\"48%\" /\u003e\n  \u003cimg src=\"https://media.giphy.com/media/Gpk4c9pHMJLbjugDmZ/giphy.gif\" width=\"48%\" /\u003e\n\u003c/p\u003e\n\n- Median Of Medians\n  - This algorithm is based on [Median of Medians](https://en.wikipedia.org/wiki/Median_of_medians) algorithm, one of the first deterministic linear time worst case median algorithm.\n  - **Location:** [`miniselect/median_of_medians.h`](./include/miniselect/median_of_medians.h).\n  - **Functions:** `median_of_medians_select`, `median_of_medians_partial_sort`.\n  - **Performance advice:** This algorithm does not show advantages over others, implemented for historical reasons and for bechmarking.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/C0txh78ngyEGqmrX7c/giphy.gif\" /\u003e\u003c/p\u003e\n\n- Median Of Ninthers\n  - This algorithm is based on [Fast Deterministic Selection](https://erdani.com/research/sea2017.pdf) paper by Andrei Alexandrescu, one of the latest and fastest deterministic linear time worst case median algorithms.\n  - **Location:** [`miniselect/median_of_ninthers.h`](./include/miniselect/median_of_ninthers.h).\n  - **Functions:** `median_of_ninthers_select`, `median_of_ninthers_partial_sort`.\n  - **Performance advice:** Use this algorithm if you absolutely need linear time worst case scenario for selection algorithm. This algorithm shows some strengths over other deterministic [`PICK`](https://en.wikipedia.org/wiki/Median_of_medians) algorithms and has lower constanst than MedianOfMedians.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/usKlqJoh1WVLWLU9Dt/giphy.gif\" /\u003e\u003c/p\u003e\n\n- Median Of 3 Random\n  - This algorithm is based on QuickSelect with the random median of 3 pivot choice algorithm (it chooses random 3 elements in the range and takes the middle value). It is a randomized algorithm.\n  - **Location:** [`miniselect/median_of_3_random.h`](./include/miniselect/median_of_3_random.h).\n  - **Functions:** `median_of_3_random_select`, `median_of_3_random_partial_sort`.\n  - **Performance advice:** This is a randomized algorithm and also it did not show any strengths against Median Of Ninthers.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/GrbIu6PvrMuvoowp3U/giphy.gif\" /\u003e\u003c/p\u003e\n\n- Introselect\n  - This algorithm is based on [Introselect](https://en.wikipedia.org/wiki/Introselect) algorithm, it is used in libstdc++ in `std::nth_element`, however instead of falling back to MedianOfMedians it is using HeapSelect which adds logarithm to its worst complexity.\n  - **Location:** `\u003calgorithm\u003e`.\n  - **Functions:** `std::nth_element`.\n  - **Performance advice:** This algorithm is used in standard library and is not recommended to use if you are looking for performance.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/VOBM4MVBpiTgkbA6CH/giphy.gif\" /\u003e\u003c/p\u003e\n\n- Median Of 3\n  - This algorithm is based on QuickSelect with median of 3 pivot choice algorithm (the middle value between begin, mid and end values), it is used in libc++ in `std::nth_element`.\n  - **Location:** `\u003calgorithm\u003e`.\n  - **Functions:** `std::nth_element`.\n  - **Performance advice:** This algorithm is used in standard library and is not recommended to use if you are looking for performance.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/03eJ0S7H79Jdtrv49F/giphy.gif\" /\u003e\u003c/p\u003e\n\n- `std::partial_sort` or `HeapSelect`\n  - This algorithm has [heap-based solutions](https://en.wikipedia.org/wiki/Partial_sorting) both in libc++ and libstdc++, from the first $k$ elements the max heap is built, then one by one the elements are trying to be pushed to that heap with HeapSort in the end.\n  - **Location:** `\u003calgorithm\u003e`, [`miniselect/heap_select.h`](./include/miniselect/heap_select.h).\n  - **Functions:** `std::partial_sort`, `heap_select`, `heap_partial_sort`.\n  - **Performance advice:** This algorithm is very good for random data and small $k$ and might outperform all selection+sort algorithms. However, for descending data it starts to significantly degrade and is not recommended for use if you have such patterns in real data.\n\n\u003cp align=\"center\"\u003e\u003cimg src=\"https://media.giphy.com/media/MAw3Tk2TDxrnv6vLlu/giphy.gif\" /\u003e\u003c/p\u003e\n\n## Other algorithms to come\n\n* Kiwiel modification of FloydRivest algorithm which is described in [On Floyd and Rivest’s SELECT algorithm](https://core.ac.uk/download/pdf/82672439.pdf) with ternary and quintary pivots.\n* Combination of FloydRivest and pdqsort pivot strategies, currently all experiments did not show any boost.\n\nPerformance results\n-------------------\n\nWe use 10 datasets and 8 algorithms with 10000000 elements to find median and\nother $k$ on `Intel(R) Core(TM) i5-4200H CPU @ 2.80GHz` for `std::vector\u003cint\u003e`,\nfor median the benchmarks are the following:\n\n![median](benches/plots/result_10000000_5000000.png)\n\n![median](benches/plots/result_comparisons_10000000_5000000.png)\n\n![median](benches/plots/result_accesses_10000000_5000000.png)\n\nFor smaller $k$,\nfor example, 1000, the results are the following\n\n![k equals 1000](benches/plots/result_10000000_1000.png)\n\n![k equals 1000](benches/plots/result_comparisons_10000000_1000.png)\n\n![k equals 1000](benches/plots/result_accesses_10000000_1000.png)\n\nOther benchmarks can be found [here](https://drive.google.com/drive/folders/1DHEaeXgZuX6AJ9eByeZ8iQVQv0ueP8XM).\n\n\nReal-world usage\n----------------\n\n- [ClickHouse Inc.](https://github.com/ClickHouse/ClickHouse): Fast Open-Source OLAP DBMS\n- [YDB](https://github.com/ydb-platform/ydb/commit/698b400d09b3c1c7aff6ebf986eb3dc3ced74a08): Open-Source Distributed SQL Database\n- [cpp-sort](https://github.com/Morwenn/cpp-sort): Largest Sorting algorithms \u0026 related tools for C++\n\nIf you are planning to use miniselect in your product, please work from one of\nour releases and if you wish, you can write the acknowledgment in this section\nfor visibility.\n\nContributing\n------------\n\nPatches are welcome with new algorithms! You should add the selection algorithm\ntogether with the partial sorting algorithm in [include](./include), add\ntests in [testing](./testing) and ideally run benchmarks to see how it performs.\nIf you also have some data cases to test against, we would be more than happy\nto merge them.\n\nMotivation\n----------\n\nThe author was surveying research on small\n$k$\nin selection algorithms and was struggling to find working implementations to\ncompare different approaches from standard library and quickselect algorithms.\nIt turned out that the problem is much more interesting than it looks, and after\nconsulting The Art of Computer Programming from Donald Knuth about\nminimum comparison sorting and selection algorithms, the author decided to look\nthrough unpopular algorithms and try them out. Not finding any satisfactory\nlibrary for selection algorithms nor research corresponding to the open source codes,\nthe author set out to write one generic library.\n\nFor a big story of adventures see\nthe author's [blog post](https://danlark.org/2020/11/11/miniselect-practical-and-generic-selection-algorithms/).\n\nLicense\n-------\n\nThe code is made available under the [Boost License 1.0](https://boost.org/LICENSE_1_0.txt).\n\nThird-Party Libraries Used and Adjusted\n---------------------------------------\n\n| Library             | License                                                                                          |\n|---------------------|--------------------------------------------------------------------------------------------------|\n| pdqsort             | [MIT](https://github.com/orlp/pdqsort/blob/47a46767d76fc852284eaa083e4b7034ee6e2559/license.txt) |\n| MedianOfNinthers    | [Boost License 1.0](https://github.com/andralex/MedianOfNinthers/blob/master/LICENSE_1_0.txt)    |\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanlark1%2Fminiselect","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanlark1%2Fminiselect","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanlark1%2Fminiselect/lists"}