2个版本
| 0.1.1 | 2024年2月18日 |
|---|---|
| 0.1.0 | 2024年2月18日 |
2572 在 算法 中
5KB
64 行
csselection_sort
在向量上实现的选择排序算法。
使用此创建为Vec数据类型添加selection_sort和selection_sort_by方法。
use csselection_sort::SelectionSort;
let mut input: Vec<u32> = vec![2, 1];
// this will sort items in ascending order
// using selection sort algorithm
input.selection_sort();
// input is now [1,2]
使用selection_sort_by来自定义项目比较的方式。将一个形式为函数的第二个参数传递:
fn(a: &T, b: &T) -> bool;
此函数必须返回true以指示a比b更靠左。例如,为了按降序对u32进行排序,by参数可以是:
fn desc(a: u32, b: u32) -> bool {
a < b
}
此示例在a=1和b==5时返回true,以确保5位于1的左侧。
为了方便,提供了asc和desc函数。
use csselection_sort::{SelectionSort, des};
let mut input: Vec<u32> = vec![1, 2];
// this will sort items in descending order
// using selection sort algorithm
input.selection_sort_by(desc);
// input is now [2,1]
调用selection_sort与调用selection_sort_by(asc)等效。