├── .github └── workflows │ ├── Build.yml │ ├── Lint.yml │ └── Tests.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── Makefile ├── README.md ├── benches └── sort.rs ├── codecov.yml └── src └── lib.rs /.github/workflows/Build.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: PartialSort Build Check 3 | 4 | jobs: 5 | test-linux: 6 | name: Build On Linux 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | target: 11 | - aarch64-unknown-linux-gnu 12 | - armv7-unknown-linux-gnueabihf 13 | - x86_64-unknown-linux-gnu 14 | - x86_64-linux-android 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: dtolnay/rust-toolchain@stable 18 | - uses: taiki-e/install-action@cross 19 | - run: cross build --release --target ${{ matrix.target }} 20 | 21 | test-mac: 22 | name: Build on Mac 23 | runs-on: macos-latest 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: dtolnay/rust-toolchain@stable 27 | - run: cargo build 28 | -------------------------------------------------------------------------------- /.github/workflows/Lint.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: PartialSort Lint 3 | 4 | jobs: 5 | fmt: 6 | name: Rustfmt 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - uses: dtolnay/rust-toolchain@stable 11 | with: 12 | components: rustfmt 13 | - run: cargo fmt --all -- --check 14 | 15 | clippy: 16 | name: Clippy 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: dtolnay/rust-toolchain@stable 21 | with: 22 | components: clippy 23 | - run: cargo clippy -- -D warnings 24 | -------------------------------------------------------------------------------- /.github/workflows/Tests.yml: -------------------------------------------------------------------------------- 1 | name: PartialSort tests 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v4 9 | - uses: dtolnay/rust-toolchain@stable 10 | - run: make test 11 | 12 | miri-checks: 13 | name: Miri 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: dtolnay/rust-toolchain@nightly 18 | with: 19 | components: miri 20 | - run: make miri 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | examples 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "partial_sort" 3 | edition = "2018" 4 | version = "1.0.0" 5 | authors = ["sundy-li <543950155@qq.com>"] 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/sundy-li/partial_sort" 8 | homepage = "https://github.com/sundy-li/partial_sort" 9 | description = "This library provide a Rust version std::partial_sort" 10 | readme = "README.md" 11 | 12 | include = ["src/", "LICENSE-*", "README.md"] 13 | 14 | [lib] 15 | name = "partial_sort" 16 | bench = false 17 | 18 | [dev-dependencies] 19 | criterion = "0.5.1" 20 | rand = "0.8.5" 21 | 22 | # Uncomment this if you want to do benchmark 23 | [[bench]] 24 | name = "sort" 25 | harness = false 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | cargo test -- --nocapture 3 | cargo test -- --ignored -- --nocapture 4 | 5 | miri: 6 | cargo miri test -- --nocapture 7 | 8 | bench: 9 | cargo bench -- --nocapture 10 | 11 | lint: 12 | cargo fmt 13 | cargo clippy -- -D warnings 14 | 15 | build: 16 | cargo build --release 17 | 18 | clean: 19 | cargo clean 20 | 21 | .PHONY: test bench lint build clean miri 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # partial_sort 2 | 3 | [![](https://img.shields.io/crates/v/partial_sort.svg)](https://crates.io/crates/partial_sort) 4 | [![](https://img.shields.io/crates/d/partial_sort.svg)](https://crates.io/crates/partial_sort) 5 | [![](https://docs.rs/partial_sort/badge.svg)](https://docs.rs/partial_sort/) 6 | [![](https://github.com/sundy-li/partial_sort/actions/workflows/Build.yml/badge.svg)](https://github.com/sundy-li/partial_sort/actions/workflows/Build.yml) 7 | 8 | partial_sort is Rust version of [std::partial_sort](https://en.cppreference.com/w/cpp/algorithm/partial_sort) 9 | 10 | ## Usage 11 | 12 | ```rust 13 | use partial_sort::PartialSort; 14 | 15 | fn main() { 16 | let mut vec = vec![4, 4, 3, 3, 1, 1, 2, 2]; 17 | vec.partial_sort(4, |a, b| a.cmp(b)); 18 | assert_eq!(&vec[0..4], &[1, 1, 2, 2]); 19 | } 20 | ``` 21 | 22 | 23 | ## Benches 24 | 25 | First we compare what happens when sorting the entire vector. 26 | 27 | Bench env: 28 | 29 | ``` 30 | $ uname -a 31 | Linux arch 6.8.7-arch1-1 #1 SMP PREEMPT_DYNAMIC Wed, 17 Apr 2024 15:20:28 +0000 x86_64 GNU/Linux 32 | 33 | $ cat /proc/cpuinfo | grep '\-Core' | head -1 34 | model name : AMD Ryzen 9 5950X 16-Core Processor 35 | ``` 36 | 37 | Bench results: 38 | 39 | ``` 40 | nth_select sort 10000 limit 20 time: [8.6016 µs 8.6123 µs 8.6236 µs] 41 | partial sort 10000 limit 20 time: [5.3522 µs 5.3565 µs 5.3610 µs] // 1.6x faster 42 | partial sort 10000 limit 200 time: [15.736 µs 15.749 µs 15.763 µs] 43 | partial sort 10000 limit 2000 time: [111.97 µs 112.07 µs 112.18 µs] 44 | partial sort 10000 limit 10000 time: [219.21 µs 222.58 µs 225.85 µs] 45 | stdsort 10000 time: [81.795 µs 82.108 µs 82.383 µs] 46 | unstable stdsort 10000 time: [65.339 µs 65.355 µs 65.373 µs] 47 | heapsort 10000 time: [241.86 µs 242.09 µs 242.29 µs] 48 | partial reverse sort 10000 limit 20 time: [5.4574 µs 5.4696 µs 5.4843 µs] 49 | stdsort reverse 10000 time: [82.680 µs 82.751 µs 82.822 µs] 50 | ``` 51 | 52 | ## License 53 | 54 | Licensed under either of 55 | 56 | * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) 57 | * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) 58 | -------------------------------------------------------------------------------- /benches/sort.rs: -------------------------------------------------------------------------------- 1 | extern crate criterion; 2 | extern crate partial_sort; 3 | extern crate rand; 4 | 5 | use std::collections::BinaryHeap; 6 | 7 | use criterion::{criterion_group, criterion_main, BatchSize, Criterion}; 8 | use partial_sort::PartialSort; 9 | use rand::distributions::{Distribution, Standard}; 10 | use rand::rngs::StdRng; 11 | use rand::{Rng, SeedableRng}; 12 | 13 | fn create_vec(size: usize) -> Vec 14 | where 15 | Standard: Distribution, 16 | { 17 | let mut rng = StdRng::seed_from_u64(42); 18 | (0..size).map(|_| rng.gen::()).collect() 19 | } 20 | 21 | fn criterion_benchmark(c: &mut Criterion) { 22 | let n = 10000; 23 | 24 | c.bench_function("nth_select sort 10000 limit 20", |b| { 25 | b.iter_batched_ref( 26 | || create_vec::(n), 27 | |v| { 28 | let (p, _, _) = v.select_nth_unstable(20); 29 | p.sort_unstable(); 30 | }, 31 | BatchSize::SmallInput, 32 | ) 33 | }); 34 | 35 | c.bench_function("partial sort 10000 limit 20", |b| { 36 | b.iter_batched_ref( 37 | || create_vec::(n), 38 | |v| v.partial_sort(20, |a, b| a.cmp(b)), 39 | BatchSize::SmallInput, 40 | ) 41 | }); 42 | 43 | c.bench_function("partial sort 10000 limit 200", |b| { 44 | b.iter_batched_ref( 45 | || create_vec::(n), 46 | |v| v.partial_sort(200, |a, b| a.cmp(b)), 47 | BatchSize::SmallInput, 48 | ) 49 | }); 50 | 51 | c.bench_function("partial sort 10000 limit 2000", |b| { 52 | b.iter_batched_ref( 53 | || create_vec::(n), 54 | |v| v.partial_sort(2000, |a, b| a.cmp(b)), 55 | BatchSize::SmallInput, 56 | ) 57 | }); 58 | 59 | c.bench_function("partial sort 10000 limit 10000", |b| { 60 | b.iter_batched_ref( 61 | || create_vec::(n), 62 | |v| v.partial_sort(10000, |a, b| a.cmp(b)), 63 | BatchSize::SmallInput, 64 | ) 65 | }); 66 | 67 | c.bench_function("stdsort 10000", |b| { 68 | b.iter_batched_ref(|| create_vec::(n), |v| v.sort(), BatchSize::SmallInput) 69 | }); 70 | 71 | c.bench_function("unstable stdsort 10000", |b| { 72 | b.iter_batched_ref( 73 | || create_vec::(n), 74 | |v| v.sort_unstable(), 75 | BatchSize::SmallInput, 76 | ) 77 | }); 78 | 79 | c.bench_function("heapsort 10000", |b| { 80 | b.iter_batched( 81 | || create_vec::(n), 82 | |v| BinaryHeap::from(v).into_sorted_vec(), 83 | BatchSize::SmallInput, 84 | ) 85 | }); 86 | 87 | c.bench_function("partial reverse sort 10000 limit 20", |b| { 88 | b.iter_batched_ref( 89 | || create_vec::(n), 90 | |v| v.partial_sort(20, |a, b| a.cmp(b).reverse()), 91 | BatchSize::SmallInput, 92 | ) 93 | }); 94 | 95 | c.bench_function("stdsort reverse 10000", |b| { 96 | b.iter_batched_ref( 97 | || create_vec::(n), 98 | |v| v.sort_by(|a, b| a.cmp(b).reverse()), 99 | BatchSize::SmallInput, 100 | ) 101 | }); 102 | } 103 | 104 | criterion_group!(benches, criterion_benchmark); 105 | criterion_main!(benches); 106 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | --- 2 | ignore: 3 | - benches/* 4 | 5 | coverage: 6 | precision: 0 7 | round: down 8 | range: "70...100" 9 | status: 10 | project: 11 | default: 12 | enabled: yes 13 | threshold: 1% 14 | patch: 15 | default: 16 | enabled: yes 17 | threshold: 1% 18 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! # partial_sort 2 | //! 3 | //! [![](https://img.shields.io/crates/d/partial_sort.svg)](https://crates.io/crates/partial_sort) 4 | //! [![](https://docs.rs/partial_sort/badge.svg)](https://docs.rs/partial_sort/) 5 | //! [![](https://github.com/sundy-li/partial_sort/actions/workflows/Build.yml/badge.svg)](https://github.com/sundy-li/partial_sort/actions/workflows/Build.yml) 6 | //! 7 | //! partial_sort is Rust version of [std::partial_sort](https://en.cppreference.com/w/cpp/algorithm/partial_sort) 8 | //! 9 | //! ```shell 10 | //! cargo add partial_sort 11 | //! ``` 12 | //! 13 | //! ## Example 14 | //! 15 | //! ```rust 16 | //! # use partial_sort::PartialSort; 17 | //! 18 | //! let mut vec = vec![4, 4, 3, 3, 1, 1, 2, 2]; 19 | //! vec.partial_sort(4, |a, b| a.cmp(b)); 20 | //! assert_eq!(&vec[0..4], &[1, 1, 2, 2]); 21 | //! ``` 22 | 23 | #![crate_type = "lib"] 24 | #![crate_name = "partial_sort"] 25 | 26 | use std::cmp::Ordering; 27 | use std::cmp::Ordering::Less; 28 | use std::{mem, ptr}; 29 | 30 | pub trait PartialSort { 31 | type Item; 32 | 33 | /// Rearranges elements such that the range `[0, last)` contains the smallest `last` elements 34 | /// in the range `[0, n)` in ascending order. 35 | fn partial_sort(&mut self, last: usize, cmp: F) 36 | where 37 | F: FnMut(&Self::Item, &Self::Item) -> Ordering; 38 | } 39 | 40 | impl PartialSort for [T] { 41 | type Item = T; 42 | 43 | fn partial_sort(&mut self, last: usize, mut cmp: F) 44 | where 45 | F: FnMut(&Self::Item, &Self::Item) -> Ordering, 46 | { 47 | partial_sort(self, last, |a, b| cmp(a, b) == Less); 48 | } 49 | } 50 | 51 | pub fn partial_sort(v: &mut [T], last: usize, mut is_less: F) 52 | where 53 | F: FnMut(&T, &T) -> bool, 54 | { 55 | assert!(last <= v.len()); 56 | 57 | make_heap(v, last, &mut is_less); 58 | 59 | for i in last..v.len() { 60 | if is_less(&v[i], &v[0]) { 61 | v.swap(0, i); 62 | adjust_heap(v, 0, last, &mut is_less); 63 | } 64 | } 65 | 66 | sort_heap(v, last, &mut is_less); 67 | } 68 | 69 | #[inline] 70 | fn make_heap(v: &mut [T], last: usize, is_less: &mut F) 71 | where 72 | F: FnMut(&T, &T) -> bool, 73 | { 74 | if last < 2 { 75 | return; 76 | } 77 | 78 | let len = last; 79 | let mut parent = (len - 2) / 2; 80 | 81 | loop { 82 | adjust_heap(v, parent, len, is_less); 83 | if parent == 0 { 84 | return; 85 | } 86 | parent -= 1; 87 | } 88 | } 89 | 90 | /// adjust_heap is a shift up adjust op for the heap 91 | #[inline] 92 | fn adjust_heap(v: &mut [T], hole_index: usize, len: usize, is_less: &mut F) 93 | where 94 | F: FnMut(&T, &T) -> bool, 95 | { 96 | assert!(len <= v.len()); 97 | assert!(hole_index < v.len()); 98 | 99 | let mut left_child = hole_index * 2 + 1; 100 | 101 | // SAFETY: Reading from a reference is always valid. The original memory 102 | // location is now conceptually moved-from. At the end of the function, 103 | // or if `is_less()` panics at any point, `hole` is dropped and fills 104 | // the moved-from location with a valid element. 105 | let tmp = mem::ManuallyDrop::new(unsafe { ptr::read(&v[hole_index]) }); 106 | let mut hole = InsertionHole { 107 | src: &*tmp, 108 | dest: &mut v[hole_index], 109 | }; 110 | 111 | while left_child < len { 112 | if left_child + 1 < len { 113 | left_child += usize::from(is_less( 114 | unsafe { v.get_unchecked(left_child) }, // SAFETY: left_child < len 115 | unsafe { v.get_unchecked(left_child + 1) }, // SAFETY: left_child + 1 < len 116 | )); 117 | } 118 | 119 | // SAFETY: left_child (even incremented) is still in bounds. 120 | if !is_less(&*tmp, unsafe { v.get_unchecked(left_child) }) { 121 | break; 122 | } 123 | 124 | // SAFETY: Source and destination are references. Now the location 125 | // at index left_child is conceptually moved-from and `hole` is updated 126 | // accordingly. At the end of the function, or if `is_less()` panics 127 | // at any point, `hole` is dropped and fills the moved-from location 128 | // with a valid element. 129 | unsafe { 130 | ptr::copy_nonoverlapping( 131 | v.get_unchecked(left_child), // SAFETY: still in bounds 132 | hole.dest, 133 | 1, 134 | ); 135 | } 136 | hole.dest = &mut v[left_child]; 137 | 138 | left_child = left_child * 2 + 1; 139 | } 140 | 141 | // When dropped, copies from `src` into `dest`. Adapted from 142 | // `std::sort_by()`. 143 | struct InsertionHole { 144 | src: *const T, 145 | dest: *mut T, 146 | } 147 | 148 | impl Drop for InsertionHole { 149 | fn drop(&mut self) { 150 | // SAFETY: `self.src` and `self.dest` have been created from 151 | // references. 152 | unsafe { 153 | ptr::copy_nonoverlapping(self.src, self.dest, 1); 154 | } 155 | } 156 | } 157 | } 158 | 159 | #[inline] 160 | fn sort_heap(v: &mut [T], mut last: usize, is_less: &mut F) 161 | where 162 | F: FnMut(&T, &T) -> bool, 163 | { 164 | while last > 1 { 165 | last -= 1; 166 | v.swap(0, last); 167 | adjust_heap(v, 0, last, is_less); 168 | } 169 | } 170 | 171 | #[cfg(test)] 172 | mod tests { 173 | use rand::Rng; 174 | use std::cmp::Ordering; 175 | use std::fmt; 176 | use std::sync::Arc; 177 | 178 | use crate::PartialSort; 179 | 180 | #[test] 181 | fn empty_test() { 182 | let mut before: Vec = vec![4, 4, 3, 3, 1, 1, 2, 2]; 183 | before.partial_sort(0, |a, b| a.cmp(b)); 184 | } 185 | 186 | #[test] 187 | fn single_test() { 188 | let mut before: Vec = vec![4, 4, 3, 3, 1, 1, 2, 2]; 189 | let last = 6; 190 | let mut d = before.clone(); 191 | d.sort(); 192 | 193 | before.partial_sort(last, |a, b| a.cmp(b)); 194 | assert_eq!(&d[0..last], &before.as_slice()[0..last]); 195 | } 196 | 197 | #[test] 198 | fn sorted_strings_test() { 199 | let mut before: Vec<&str> = vec![ 200 | "a", "cat", "mat", "on", "sat", "the", "xxx", "xxxx", "fdadfdsf", 201 | ]; 202 | let last = 6; 203 | let mut d = before.clone(); 204 | d.sort(); 205 | 206 | before.partial_sort(last, |a, b| a.cmp(b)); 207 | assert_eq!(&d[0..last], &before.as_slice()[0..last]); 208 | } 209 | 210 | #[test] 211 | fn sorted_ref_test() { 212 | trait TModel: fmt::Debug + Send + Sync { 213 | fn size(&self) -> usize; 214 | } 215 | 216 | struct ModelFoo { 217 | size: usize, 218 | } 219 | 220 | impl TModel for ModelFoo { 221 | fn size(&self) -> usize { 222 | self.size 223 | } 224 | } 225 | impl fmt::Debug for ModelFoo { 226 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 227 | write!(f, "ModelFoo[{}]", self.size)?; 228 | Ok(()) 229 | } 230 | } 231 | 232 | struct ModelBar { 233 | size: usize, 234 | } 235 | 236 | impl TModel for ModelBar { 237 | fn size(&self) -> usize { 238 | self.size 239 | } 240 | } 241 | impl fmt::Debug for ModelBar { 242 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 243 | write!(f, "ModelBar[{}]", self.size)?; 244 | Ok(()) 245 | } 246 | } 247 | 248 | type ModelRef = Arc; 249 | 250 | /// Compare two `Array`s based on the ordering defined in [ord](crate::array::ord). 251 | fn cmp_model(a: &dyn TModel, b: &dyn TModel) -> Ordering { 252 | a.size().cmp(&b.size()) 253 | } 254 | 255 | let mut before: Vec<(i32, ModelRef)> = vec![ 256 | (1i32, Arc::new(ModelBar { size: 100 })), 257 | (1i32, Arc::new(ModelFoo { size: 99 })), 258 | (1i32, Arc::new(ModelFoo { size: 101 })), 259 | (1i32, Arc::new(ModelBar { size: 104 })), 260 | (1i32, Arc::new(ModelBar { size: 10 })), 261 | (1i32, Arc::new(ModelBar { size: 24 })), 262 | (1i32, Arc::new(ModelBar { size: 34 })), 263 | (1i32, Arc::new(ModelBar { size: 114 })), 264 | ]; 265 | 266 | let last = 6; 267 | let mut d = before.clone(); 268 | d.sort_by(|a, b| cmp_model(a.1.as_ref(), b.1.as_ref())); 269 | 270 | before.partial_sort(last, |a, b| cmp_model(a.1.as_ref(), b.1.as_ref())); 271 | 272 | d[0..last].iter().zip(&before[0..last]).for_each(|(a, b)| { 273 | assert_eq!(a.0, b.0); 274 | assert_eq!(a.1.size(), b.1.size()); 275 | }); 276 | } 277 | 278 | /// creates random initial vectors, partial sorts then and 279 | /// verifies the result against std's `sort`. 280 | #[test] 281 | fn sorted_random_u64_test() { 282 | let mut rng = rand::thread_rng(); 283 | let vec_size = 1025; 284 | let partial_size = (rng.gen::() % vec_size) as usize; 285 | let mut data = (0u64..vec_size) 286 | .map(|_| rng.gen::()) 287 | .collect::>(); 288 | let mut d = data.clone(); 289 | d.sort(); 290 | 291 | data.partial_sort(partial_size, |a, b| a.cmp(b)); 292 | assert_eq!(&d[0..partial_size], &data.as_slice()[0..partial_size]); 293 | } 294 | 295 | #[test] 296 | #[ignore] 297 | fn sorted_expensive_random_u64_test() { 298 | for _ in 0..100 { 299 | let mut rng = rand::thread_rng(); 300 | let vec_size = 1025; 301 | let partial_size = (rng.gen::() % vec_size) as usize; 302 | let mut data = (0u64..vec_size) 303 | .map(|_| rng.gen::()) 304 | .collect::>(); 305 | let mut d = data.clone(); 306 | d.sort(); 307 | 308 | data.partial_sort(partial_size, |a, b| a.cmp(b)); 309 | assert_eq!(&d[0..partial_size], &data.as_slice()[0..partial_size]); 310 | } 311 | } 312 | } 313 | --------------------------------------------------------------------------------