Created
October 31, 2022 01:04
-
-
Save ssrlive/bc37156d959aba57eecab640a74d25df to your computer and use it in GitHub Desktop.
Quick sort in rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pub fn quick_sort<T: Ord + Copy>(slice: &mut [T]) { | |
| if slice.len() <= 1 { | |
| return; | |
| } | |
| let p = slice[0]; | |
| let (mut left, mut right): (Vec<T>, Vec<T>) = slice[1..].iter().partition(|&x| *x < p); | |
| quick_sort(&mut left); | |
| quick_sort(&mut right); | |
| slice.copy_from_slice(&[left, vec![p], right].concat()); | |
| } | |
| #[test] | |
| fn test_quick_sort() { | |
| let mut v = vec![4, 2, 3, 1, 3, 8]; | |
| quick_sort(&mut v); | |
| assert_eq!(v, &[1, 2, 3, 3, 4, 8]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment