├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── bin └── bench.rs ├── bubblesort.rs ├── heapsort.rs ├── insertionsort.rs ├── lib.rs ├── quicksort.rs ├── radixsort.rs └── selectionsort.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | /Rplots.pdf 4 | /values.dat 5 | /.RData 6 | /.Rhistory 7 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "orst" 3 | version = "0.1.0" 4 | authors = ["Jon Gjengset "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | rand = "0.7" 11 | -------------------------------------------------------------------------------- /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 2020 Jon Gjengset 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 | MIT License 2 | 3 | Copyright (c) 2020 Jon Gjengset 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Implementation of various [sorting algorithms] in Rust from [this live 2 | stream]. 3 | 4 | To benchmark and plot (you'll need [R] and [ggplot2]): 5 | 6 | ```console 7 | $ cargo r --release > values.dat 8 | $ R 9 | t <- read.table('values.dat', header=TRUE) 10 | library(ggplot2) 11 | # to plot # comparisons 12 | ggplot(t, aes(n, comparisons, colour = algorithm)) + geom_point() + scale_y_log10() 13 | # to plot runtime 14 | ggplot(t, aes(n, time, colour = algorithm)) + geom_point() + scale_y_log10() 15 | ``` 16 | 17 | [sorting algorithms]: https://en.wikipedia.org/wiki/Sorting_algorithm 18 | [this live stream]: https://www.youtube.com/watch?v=h4RkCyJyXmM 19 | [R]: https://www.r-project.org/ 20 | [ggplot2]: https://ggplot2.tidyverse.org/ 21 | -------------------------------------------------------------------------------- /src/bin/bench.rs: -------------------------------------------------------------------------------- 1 | use orst::*; 2 | 3 | use rand::prelude::*; 4 | use std::cell::Cell; 5 | use std::cmp::Ordering; 6 | use std::rc::Rc; 7 | 8 | #[derive(Clone)] 9 | struct SortEvaluator { 10 | t: T, 11 | cmps: Rc>, 12 | } 13 | 14 | impl PartialEq for SortEvaluator { 15 | fn eq(&self, other: &Self) -> bool { 16 | self.cmps.set(self.cmps.get() + 1); 17 | self.t == other.t 18 | } 19 | } 20 | impl Eq for SortEvaluator {} 21 | 22 | impl PartialOrd for SortEvaluator { 23 | fn partial_cmp(&self, other: &Self) -> Option { 24 | self.cmps.set(self.cmps.get() + 1); 25 | self.t.partial_cmp(&other.t) 26 | } 27 | } 28 | impl Ord for SortEvaluator { 29 | fn cmp(&self, other: &Self) -> Ordering { 30 | self.cmps.set(self.cmps.get() + 1); 31 | self.t.cmp(&other.t) 32 | } 33 | } 34 | 35 | impl Bytify for SortEvaluator 36 | where 37 | T: Bytify 38 | { 39 | fn bytify(&self, level: usize) -> Option 40 | { 41 | return self.t.bytify(level); 42 | } 43 | } 44 | 45 | fn main() { 46 | let mut rand = rand::thread_rng(); 47 | let counter = Rc::new(Cell::new(0)); 48 | 49 | println!("algorithm n comparisons time"); 50 | for &n in &[0, 1, 10, 100, 1000, 10000, 50000] { 51 | let mut values = Vec::with_capacity(n); 52 | for _ in 0..n { 53 | values.push(SortEvaluator { 54 | t: rand.gen::(), 55 | cmps: Rc::clone(&counter), 56 | }); 57 | } 58 | 59 | for _ in 0..10 { 60 | values.shuffle(&mut rand); 61 | 62 | let took = bench(BubbleSort, &values, &counter); 63 | println!("{} {} {} {}", "bubble", n, took.0, took.1); 64 | let took = bench(InsertionSort { smart: true }, &values, &counter); 65 | println!("{} {} {} {}", "insertion-smart", n, took.0, took.1); 66 | let took = bench(InsertionSort { smart: false }, &values, &counter); 67 | println!("{} {} {} {}", "insertion-dumb", n, took.0, took.1); 68 | let took = bench(SelectionSort, &values, &counter); 69 | println!("{} {} {} {}", "selection", n, took.0, took.1); 70 | let took = bench(QuickSort, &values, &counter); 71 | println!("{} {} {} {}", "quick", n, took.0, took.1); 72 | let took = bench(RadixSort, &values, &counter); 73 | println!("{} {} {} {}", "radix", n, took.0, took.1); 74 | let took = bench(HeapSort, &values, &counter); 75 | println!("{} {} {} {}", "heap", n, took.0, took.1); 76 | let took = bench(StdSorter, &values, &counter); 77 | println!("{} {} {} {}", "stdstable", n, took.0, took.1); 78 | let took = bench(StdUnstableSorter, &values, &counter); 79 | println!("{} {} {} {}", "stdunstable", n, took.0, took.1); 80 | } 81 | } 82 | } 83 | 84 | fn bench>>( 85 | sorter: S, 86 | values: &[SortEvaluator], 87 | counter: &Cell, 88 | ) -> (usize, f64) { 89 | let mut values: Vec<_> = values.to_vec(); 90 | counter.set(0); 91 | let time = std::time::Instant::now(); 92 | sorter.sort(&mut values); 93 | let took = time.elapsed(); 94 | let count = counter.get(); 95 | // assert!(values.is_sorted()); 96 | for i in 1..values.len() { 97 | assert!(values[i] >= values[i - 1]); 98 | } 99 | (count, took.as_secs_f64()) 100 | } 101 | -------------------------------------------------------------------------------- /src/bubblesort.rs: -------------------------------------------------------------------------------- 1 | use super::Sorter; 2 | 3 | pub struct BubbleSort; 4 | 5 | impl Sorter for BubbleSort { 6 | fn sort(&self, slice: &mut [T]) 7 | where 8 | T: Ord, 9 | { 10 | let mut swapped = true; 11 | while swapped { 12 | swapped = false; 13 | for i in 1..slice.len() { 14 | if slice[i - 1] > slice[i] { 15 | slice.swap(i - 1, i); 16 | swapped = true; 17 | } 18 | } 19 | } 20 | } 21 | } 22 | 23 | #[test] 24 | fn it_works() { 25 | let mut things = vec![4, 2, 5, 3, 1]; 26 | BubbleSort.sort(&mut things); 27 | assert_eq!(things, &[1, 2, 3, 4, 5]); 28 | } 29 | -------------------------------------------------------------------------------- /src/heapsort.rs: -------------------------------------------------------------------------------- 1 | use super::Sorter; 2 | 3 | /// This is an in-place heapsort implementation. The code here is heavily 4 | /// inspired by the Geeks for Geeks article on the topic, which can be found 5 | /// [here](https://www.geeksforgeeks.org/heap-sort/). 6 | /// This implementation uses a max-heap to sort the provided slice in ascending 7 | /// order. 8 | pub struct HeapSort; 9 | impl Sorter for HeapSort { 10 | fn sort(&self, slice: &mut [T]) 11 | where 12 | T: Ord, 13 | { 14 | // turn `slice` into a heap 15 | for i in (0..(slice.len() / 2)).rev() { 16 | heapify(slice, i); 17 | } 18 | 19 | // perform heapsort 20 | for unsorted in (0..slice.len()).rev() { 21 | // we have a valid max heap here, so remove the top 22 | slice.swap(0, unsorted); 23 | 24 | // now we want to make sure that the rest is also sorted 25 | heapify(&mut slice[..unsorted], 0); 26 | } 27 | } 28 | } 29 | 30 | fn heapify(slice: &mut [T], root: usize) { 31 | let mut largest = root; 32 | let left = 2 * root + 1; 33 | let right = 2 * root + 2; 34 | let n = slice.len(); 35 | 36 | if left < n && slice[left] > slice[largest] { 37 | largest = left; 38 | } 39 | if right < n && slice[right] > slice[largest] { 40 | largest = right; 41 | } 42 | // at this point, `largest` points at the largest of root and its children 43 | 44 | if largest != root { 45 | slice.swap(largest, root); 46 | heapify(slice, largest); 47 | } 48 | } 49 | 50 | #[cfg(test)] 51 | mod tests { 52 | use super::*; 53 | 54 | #[test] 55 | fn arbitrary_array() { 56 | let mut slice = [1, 5, 4, 2, 3]; 57 | HeapSort.sort(&mut slice); 58 | assert_eq!(slice, [1, 2, 3, 4, 5]); 59 | } 60 | 61 | #[test] 62 | fn sorted_array() { 63 | let mut slice = (1..10).into_iter().collect::>(); 64 | HeapSort.sort(&mut slice); 65 | assert_eq!(slice, (1..10).into_iter().collect::>()); 66 | } 67 | 68 | #[test] 69 | fn very_unsorted() { 70 | let mut slice = (1..10000).into_iter().rev().collect::>(); 71 | HeapSort.sort(&mut slice); 72 | assert_eq!(slice, (1..10000).into_iter().collect::>()); 73 | } 74 | 75 | #[test] 76 | fn simple_edge_cases() { 77 | let mut one = vec![1]; 78 | HeapSort.sort(&mut one); 79 | assert_eq!(one, vec![1]); 80 | 81 | let mut two = vec![1, 2]; 82 | HeapSort.sort(&mut two); 83 | assert_eq!(two, vec![1, 2]); 84 | 85 | let mut two = vec![2, 1]; 86 | HeapSort.sort(&mut two); 87 | assert_eq!(two, vec![1, 2]); 88 | 89 | let mut three = vec![3, 1, 2]; 90 | HeapSort.sort(&mut three); 91 | assert_eq!(three, vec![1, 2, 3]); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/insertionsort.rs: -------------------------------------------------------------------------------- 1 | use super::Sorter; 2 | 3 | pub struct InsertionSort { 4 | pub smart: bool, 5 | } 6 | 7 | impl Sorter for InsertionSort { 8 | fn sort(&self, slice: &mut [T]) 9 | where 10 | T: Ord, 11 | { 12 | // [ sorted | not sorted ] 13 | for unsorted in 1..slice.len() { 14 | // slice[unsorted..] is not sorted 15 | // take slice[unsorted] and place in sorted location in slice[..=unsorted] 16 | // [ 1 3 4 | 2 ] 17 | // [ 1 3 4 2 | ] 18 | // [ 1 3 2 4 | ] 19 | // [ 1 2 3 4 | ] 20 | if !self.smart { 21 | let mut i = unsorted; 22 | while i > 0 && slice[i - 1] > slice[i] { 23 | slice.swap(i - 1, i); 24 | i -= 1; 25 | } 26 | } else { 27 | // use binary search to find index 28 | // then use .insert to splice in i 29 | let i = match slice[..unsorted].binary_search(&slice[unsorted]) { 30 | // [ a, c, e].binary_search(c) => Ok(1) 31 | Ok(i) => i, 32 | // [ a, c, e].binary_search(b) => Err(1) 33 | Err(i) => i, 34 | }; 35 | slice[i..=unsorted].rotate_right(1); 36 | } 37 | } 38 | } 39 | } 40 | 41 | #[test] 42 | fn it_works_dumb() { 43 | let mut things = vec![4, 2, 5, 3, 1]; 44 | InsertionSort { smart: false }.sort(&mut things); 45 | assert_eq!(things, &[1, 2, 3, 4, 5]); 46 | } 47 | 48 | #[test] 49 | fn it_works_smart() { 50 | let mut things = vec![4, 2, 5, 3, 1]; 51 | InsertionSort { smart: true }.sort(&mut things); 52 | assert_eq!(things, &[1, 2, 3, 4, 5]); 53 | } 54 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | pub trait Sorter{ 2 | fn sort(&self, slice: &mut [T]) 3 | where 4 | T: Ord; 5 | } 6 | 7 | mod bubblesort; 8 | mod insertionsort; 9 | mod quicksort; 10 | mod selectionsort; 11 | mod radixsort; 12 | mod heapsort; 13 | 14 | pub use bubblesort::BubbleSort; 15 | pub use insertionsort::InsertionSort; 16 | pub use quicksort::QuickSort; 17 | pub use selectionsort::SelectionSort; 18 | pub use radixsort::RadixSort; 19 | pub use radixsort::Bytify; 20 | pub use heapsort::HeapSort; 21 | 22 | pub struct StdSorter; 23 | impl Sorter for StdSorter { 24 | fn sort(&self, slice: &mut [T]) 25 | where 26 | T: Ord, 27 | { 28 | slice.sort(); 29 | } 30 | } 31 | 32 | pub struct StdUnstableSorter; 33 | impl Sorter for StdUnstableSorter { 34 | fn sort(&self, slice: &mut [T]) 35 | where 36 | T: Ord, 37 | { 38 | slice.sort_unstable(); 39 | } 40 | } 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use super::*; 45 | 46 | #[test] 47 | fn std_works() { 48 | let mut things = vec![4, 2, 3, 1]; 49 | StdSorter.sort(&mut things); 50 | assert_eq!(things, &[1, 2, 3, 4]); 51 | } 52 | 53 | #[test] 54 | fn stdunstable_works() { 55 | let mut things = vec![4, 2, 3, 1]; 56 | StdUnstableSorter.sort(&mut things); 57 | assert_eq!(things, &[1, 2, 3, 4]); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/quicksort.rs: -------------------------------------------------------------------------------- 1 | use super::Sorter; 2 | 3 | pub struct QuickSort; 4 | 5 | fn quicksort(slice: &mut [T]) { 6 | match slice.len() { 7 | 0 | 1 => return, 8 | 2 => { 9 | if slice[0] > slice[1] { 10 | slice.swap(0, 1); 11 | } 12 | return; 13 | } 14 | _ => {} 15 | } 16 | 17 | let (pivot, rest) = slice.split_first_mut().expect("slice is non-empty"); 18 | let mut left = 0; 19 | let mut right = rest.len() - 1; 20 | while left <= right { 21 | if &rest[left] <= pivot { 22 | // already on the correct side 23 | left += 1; 24 | } else if &rest[right] > pivot { 25 | // right already on the correct side 26 | // avoid unnecessary swaps back and forth 27 | if right == 0 { 28 | // we must be done 29 | break; 30 | } 31 | right -= 1; 32 | } else { 33 | // left holds a right, and right holds a left, swap them. 34 | rest.swap(left, right); 35 | left += 1; 36 | if right == 0 { 37 | // we must be done 38 | break; 39 | } 40 | right -= 1; 41 | } 42 | } 43 | 44 | // re-align left to account for the pivot at 0 45 | let left = left + 1; 46 | 47 | // place the pivot at its final location 48 | slice.swap(0, left - 1); 49 | 50 | // split_at_mut(mid: usize) -> (&mut [..mid), &mut [mid..]) 51 | let (left, right) = slice.split_at_mut(left - 1); 52 | assert!(left.last() <= right.first()); 53 | quicksort(left); 54 | quicksort(&mut right[1..]); 55 | } 56 | 57 | impl Sorter for QuickSort { 58 | fn sort(&self, slice: &mut [T]) 59 | where 60 | T: Ord, 61 | { 62 | // [ unsorted | pivot | unsorted ] 63 | quicksort(slice) 64 | } 65 | } 66 | 67 | #[test] 68 | fn it_works() { 69 | let mut things = vec![4, 2, 5, 3, 1]; 70 | QuickSort.sort(&mut things); 71 | assert_eq!(things, &[1, 2, 3, 4, 5]); 72 | } 73 | -------------------------------------------------------------------------------- /src/radixsort.rs: -------------------------------------------------------------------------------- 1 | /*! 2 | An implementation of American Flag sort (https://en.wikipedia.org/wiki/American_flag_sort), in particular inspired by M. Skarupke's 2017 C++Now talk "Sorting in less than O(n log n): Generalizing and optimizing radix sort" (https://www.youtube.com/watch?v=zqs87a_7zxw). 3 | 4 | It sorts the slice into 256 buckets (stripes) according to the most significant byte. Then it recursively sorts each bucket with more than one element in it until there are no more bytes to sort by. 5 | 6 | Currently only works on `&[T: Sized]`, as it uses `std::mem::size_of::()` to decide that it is done with the recursion. In order to be able to sort `&[T: ?Sized]`, it must be rewritten to accomodate the fact that some `T` are longer than others. 7 | */ 8 | 9 | use super::Sorter; 10 | 11 | #[cfg(test)] 12 | use rand::seq::SliceRandom; 13 | #[cfg(test)] 14 | use rand::thread_rng; 15 | 16 | pub struct RadixSort; 17 | 18 | /// Implementing this trait means that an object can be turned into a collection of `u8` keys of decreasing 19 | /// significance, to accomodate the radix sort. 20 | pub trait Bytify 21 | { 22 | /// Returns the `(n+1)`th most significant byte of `self`, recast to `usize` because it is 23 | /// exclusively used as an index into arrays. A return of `None` means that `n` goes beyond all 24 | /// the bytes that `self` can signify. 25 | /// 26 | /// # Example 27 | /// ``` 28 | /// use orst::Bytify; 29 | /// let x: u8 = 5; 30 | /// assert_eq!(x.bytify(0), Some(5 as usize)); 31 | /// assert_eq!(x.bytify(1), None); 32 | /// ``` 33 | fn bytify(&self, n: usize) -> Option; 34 | } 35 | 36 | impl Bytify for u8 37 | { 38 | fn bytify(&self, n: usize) -> Option 39 | { 40 | if n == 0 { 41 | return Some(*self as usize); 42 | } 43 | else { 44 | return None; 45 | } 46 | } 47 | } 48 | 49 | impl Bytify for usize 50 | { 51 | fn bytify(&self, n: usize) -> Option 52 | { 53 | let bytes = self.to_be_bytes(); 54 | if n >= bytes.len() 55 | { 56 | return None; 57 | } 58 | return Some(bytes[n] as usize); 59 | } 60 | } 61 | 62 | impl Bytify for i32 63 | { 64 | fn bytify(&self, n: usize) -> Option 65 | { 66 | if n >= std::mem::size_of::() 67 | { 68 | return None; 69 | } 70 | let mut b = self.to_be_bytes()[n]; 71 | if n == 0 72 | { 73 | b = b.wrapping_add(128); 74 | } 75 | return Some(b as usize); 76 | } 77 | } 78 | 79 | fn radix_sort(slice: &mut [T], level: usize) 80 | where 81 | T: Bytify + Sized, 82 | { 83 | let mut counts: [usize; 256] = [0; 256]; 84 | let mut prefix_sums: [usize; 256] = [0; 256]; 85 | let mut prefix_sums_shift: [usize; 256] = [0; 256]; 86 | 87 | for i in slice.iter() 88 | { 89 | counts[i.bytify(level).unwrap()] += 1; 90 | } 91 | 92 | let mut total: usize = 0; 93 | for i in 0..256 94 | { 95 | prefix_sums[i] = total; 96 | total += counts[i]; 97 | prefix_sums_shift[i] = total; 98 | } 99 | 100 | let mut i: usize = 0; 101 | while i < slice.len() 102 | { 103 | let j = slice[i].bytify(level).unwrap(); 104 | if prefix_sums[j] == prefix_sums_shift[j] 105 | { 106 | i += 1; 107 | continue; 108 | } 109 | if prefix_sums[j] == i 110 | { 111 | prefix_sums[j] += 1; 112 | i += 1; 113 | continue; 114 | } 115 | slice.swap(i, prefix_sums[j]); 116 | prefix_sums[j] += 1; 117 | } 118 | if std::mem::size_of::() <= level + 1 119 | { 120 | return; 121 | } 122 | if prefix_sums[0] > 1 123 | { 124 | radix_sort(&mut slice[0..prefix_sums[0]], level + 1); 125 | } 126 | for k in 1..256 127 | { 128 | if prefix_sums[k-1] + 1 < prefix_sums[k] 129 | { 130 | radix_sort(&mut slice[prefix_sums[k-1]..prefix_sums[k]], level + 1); 131 | } 132 | } 133 | } 134 | 135 | impl Sorter for RadixSort 136 | where 137 | T: Bytify, 138 | { 139 | fn sort(&self, slice: &mut [T]) 140 | { 141 | radix_sort(slice, 0); 142 | } 143 | } 144 | 145 | #[test] 146 | fn it_works() { 147 | let mut nums: Vec = (0..600).collect(); 148 | let mut rng = thread_rng(); 149 | for _ in 0..100 150 | { 151 | nums.shuffle(&mut rng); 152 | RadixSort.sort(&mut nums[..]); 153 | assert_eq!(nums, (0..600).collect::>()); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/selectionsort.rs: -------------------------------------------------------------------------------- 1 | use super::Sorter; 2 | 3 | pub struct SelectionSort; 4 | 5 | impl Sorter for SelectionSort { 6 | fn sort(&self, slice: &mut [T]) 7 | where 8 | T: Ord, 9 | { 10 | // [ sorted | not sorted ] 11 | for unsorted in 0..slice.len() { 12 | let smallest_in_rest = slice[unsorted..] 13 | .iter() 14 | .enumerate() 15 | .min_by_key(|&(_, v)| v) 16 | .map(|(i, _)| unsorted + i) 17 | .expect("slice is non-empty"); 18 | 19 | if unsorted != smallest_in_rest { 20 | slice.swap(unsorted, smallest_in_rest); 21 | } 22 | } 23 | } 24 | } 25 | 26 | #[test] 27 | fn it_works() { 28 | let mut things = vec![4, 2, 5, 3, 1]; 29 | SelectionSort.sort(&mut things); 30 | assert_eq!(things, &[1, 2, 3, 4, 5]); 31 | } 32 | --------------------------------------------------------------------------------