好的,这里为您总结了 C++、Java、Python、Golang 和 Rust 这些主流语言的排序方法,特别是自定义排序的实现方式。
概述
| 语言 | 内置排序方法 | 主要特点 | 自定义排序核心 |
|---|
| C++ | std::sort | 非常高效,通常是 IntroSort | 函数对象 (Functor)、Lambda、普通函数 |
| Java | Arrays.sort(), Collections.sort() | 对象使用 TimSort,基础类型使用快速排序 | Comparator 接口(Lambda 或匿名类) |
| Python | sorted(), list.sort() | 稳定,使用 TimSort | key 函数 或 cmp 函数(老式,不推荐) |
| Golang | sort.Sort(), sort.Slice() | 使用快速排序 | 实现 sort.Interface 或使用 sort.Slice 与 Less 函数 |
| Rust | slice.sort(), vec.sort() | 稳定,使用归并排序(TimSort 变种) | 闭包 (Closure) 传递给 sort_by 或实现 Ord/PartialOrd |
C++
C++ 主要使用 <algorithm> 库中的 std::sort 函数,它非常高效。
对基本容器(如 vector<int>)排序
1 2 3 4 5 6 7 8
| #include <algorithm> #include <vector>
std::vector<int> vec = {4, 2, 5, 3, 1};
std::sort(vec.begin(), vec.end());
std::sort(vec.begin(), vec.end(), std::greater<int>());
|
自定义排序(Lambda - 最常用)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| struct Person { std::string name; int age; };
std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 23}};
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.age < b.age; });
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) { return a.name > b.name; });
|
自定义排序(函数对象 - Functor)
1 2 3 4 5 6 7
| struct CompareByAge { bool operator()(const Person& a, const Person& b) const { return a.age < b.age; } };
std::sort(people.begin(), people.end(), CompareByAge());
|
Java
Java 对数组使用 Arrays.sort(),对集合使用 Collections.sort()。自定义排序通过 Comparator 接口实现。
Comparator 接口原型
Comparator 是一个函数式接口,核心方法原型如下:
1 2 3 4 5 6 7 8 9 10
| @FunctionalInterface public interface Comparator<T> {
int compare(T o1, T o2); }
|
Lambda 表达式原型:
返回值约定:
- 返回负数(如 -1):a 应排在 b 前面(升序)
- 返回零:a 和 b 相等
- 返回正数(如 1):a 应排在 b 后面(降序)
对数组和列表排序
1 2 3 4 5 6 7 8 9 10
| import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; import java.util.Comparator;
int[] arr = {4, 2, 5, 3, 1}; Arrays.sort(arr);
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(4, 2, 5, 3, 1)); Collections.sort(list);
|
自定义排序(Lambda - Java 8+)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Person { String name; int age; }
ArrayList<Person> people = new ArrayList<>();
people.sort((a, b) -> a.age - b.age);
Collections.sort(people, (a, b) -> a.age - b.age);
people.sort(Comparator.comparing(Person::getName));
people.sort(Comparator.comparing(Person::getName).reversed());
|
自定义排序(匿名类 - 传统方式)
1 2 3 4 5 6
| Collections.sort(people, new Comparator<Person>() { @Override public int compare(Person a, Person b) { return a.age - b.age; } });
|
Python
Python 使用内置的 sorted() 函数(返回新列表)或列表的 sort() 方法(原地修改)。推荐使用 key 参数进行自定义排序。
基本排序
1 2 3 4 5 6 7 8
| my_list = [4, 2, 5, 3, 1]
sorted_list = sorted(my_list) my_list.sort()
sorted_list = sorted(my_list, reverse=True) my_list.sort(reverse=True)
|
自定义排序(使用 key 参数 - 推荐)
key 函数将一个元素映射为一个用于比较的键。
1 2 3 4 5 6 7 8 9 10
| people = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 20}, {'name': 'Charlie', 'age': 23} ]
sorted_people = sorted(people, key=lambda x: x['age'])
sorted_people = sorted(people, key=lambda x: x['name'], reverse=True)
|
如果需要更复杂的比较逻辑(例如先按年龄比,再按姓名比),可以使用老式的比较函数。
1 2 3 4 5 6 7 8 9 10
| from functools import cmp_to_key
def compare(a, b): if a['age'] != b['age']: return a['age'] - b['age'] else: return -1 if a['name'] > b['name'] else 1
sorted_people = sorted(people, key=cmp_to_key(compare))
|
Golang
Go 的排序在 sort 包中。自定义排序有两种主流方式:1) 实现 sort.Interface;2) 使用 sort.Slice(更简单)。
基本类型排序
1 2 3 4 5 6 7
| import "sort"
ints := []int{4, 2, 5, 3, 1} sort.Ints(ints)
strs := []string{"Charlie", "Alice", "Bob"} sort.Strings(strs)
|
自定义排序(实现 sort.Interface)
需要为自定义类型实现 Len(), Less(i, j int) bool, Swap(i, j int) 三个方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| type Person struct { Name string Age int }
type ByAge []Person
func (a ByAge) Len() int { return len(a) } func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() { people := []Person{{"Alice", 25}, {"Bob", 20}, {"Charlie", 23}} sort.Sort(ByAge(people)) }
|
自定义排序(使用 sort.Slice - 更简单常用)
只需提供一个 Less 函数即可。
1 2 3 4 5 6 7 8 9 10 11
| people := []Person{{"Alice", 25}, {"Bob", 20}, {"Charlie", 23}}
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
sort.Slice(people, func(i, j int) bool { return people[i].Name > people[j].Name })
|
Rust
Rust 中,可变切片(&mut [T])和向量(Vec<T>)有 sort 方法。对于自定义排序,通常使用 sort_by 并传入一个闭包(Closure)。
基本排序
1 2 3
| let mut vec = vec![4, 2, 5, 3, 1]; vec.sort(); vec.sort_unstable();
|
自定义排序(使用 sort_by 和闭包)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #[derive(Debug)] struct Person { name: String, age: u32, }
fn main() { let mut people = vec![ Person { name: "Alice".to_string(), age: 25 }, Person { name: "Bob".to_string(), age: 20 }, Person { name: "Charlie".to_string(), age: 23 }, ];
people.sort_by(|a, b| a.age.cmp(&b.age)); people.sort_by(|a, b| b.name.cmp(&a.name)); people.sort_by(|a, b| a.age.cmp(&b.age).then_with(|| a.name.cmp(&b.name))); }
|
为自定义类型实现 Ord/PartialOrd Trait
如果希望你的类型可以直接使用 sort() 方法,需要为其实现 Ord 和 PartialOrd Trait。
1 2 3 4 5 6 7
| #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)] struct Person { age: u32, name: String, }
|
总结与建议
- C++: Lambda 是自定义
std::sort 时最现代和简洁的方式。 - Java: Lambda 和
Comparator.comparing 是 Java 8 之后的首选,非常表达意图。 - Python:
key 函数是绝对的主流,简单高效。仅在复杂比较逻辑时才考虑 cmp_to_key。 - Golang:
sort.Slice 是大多数情况下的最佳选择,避免了实现整个接口的繁琐。 - Rust: 闭包与
sort_by 是最灵活和常用的组合。为类型实现 Ord 则使其拥有默认的排序行为。