Created
April 15, 2022 02:31
-
-
Save yunyuyuan/4edb4a4f28c93746a00f14bb89538aab to your computer and use it in GitHub Desktop.
rust quick sort
This file contains 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
fn main() { | |
let mut list = vec![ | |
12, 43, 54, 324, 1, 5, 6, 23, 98, 34, 65, 32, 58, 31, 4, 673, | |
]; | |
let len = list.len(); | |
quick_sort(&mut list, 0, len); | |
println!("{:?}", list); | |
} | |
fn quick_sort(list: &mut Vec<i32>, left: usize, right: usize) { | |
if left < right { | |
let mid = partition(list, left, right); | |
quick_sort(list, left, mid - 1); | |
quick_sort(list, mid + 1, right); | |
} | |
} | |
fn partition(list: &mut Vec<i32>, left: usize, right: usize) -> usize { | |
// 用left值为默认的pivot | |
let pivot = left; | |
// 位于index之前的值,都是比pivot小的 | |
let mut index = pivot + 1; | |
for i in index..right { | |
if list[i] < list[pivot] { | |
// 如果i值小于pivot值,把i当前的值与index替换,然后index往后移一位 | |
swap(i, index, list); | |
index += 1; | |
} | |
} | |
// 遍历完成,替换pivot和index-1的位置,使得pivot前的值都比他小 | |
swap(pivot, index - 1, list); | |
// 返回mid位置 | |
index - 1 | |
} | |
fn swap(x: usize, y: usize, list: &mut Vec<i32>) { | |
list.swap(x, y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment