ng namespace std;
void Print(std::string message,const std::vector<int>& vec)
{
cout << message << ": ";
for(const auto c : vec)
cout << c << " ";
cout <<endl;
}
int main()
{
std::vector<int> myVector{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
// 1. 以默认的排序规则
std::partial_sort(myVector.begin(),myVector.begin() + 4,myVector.end());
Print("Sorted Default", myVector);
// 2. 以标准库的greater函数进行排序
std::partial_sort(myVector.begin(),myVector.end(),std::greater<int>());
Print("Sorted Standard Compare Function",myVector);
// 3.以自定义的函数定义排序规则
// lamda 表达式
auto cmp1 = [](const int a,const int b)
{
return a < b;
};
std::sort(myVector.begin(),myVector.end(),cmp1);
Print("Sorted Lamda Function",myVector);
return 0;
}
Sorted Default: 0 1 2 3 8 7 6 9 5 4 Sorted Standard Compare Function: 9 8 7 6 5 0 1 2 3 4 Sorted Lamda Function: 0 1 9 8 7 6 5 2 3 4
笔者在用C++复刻C#代码的时候发现对相同的数组排序的结果有时候会出现不一致,查了C#的官方文档后才发现,C#中Array.Sort()函数是unstable_sort,也就是说其排序是无法保证相对顺序的,而且Array似乎也没有提供Stable_Sort版本的排序函数,因此如果需要保证相对顺序不变,需要手动给原始的数据添加一个index,这样再其他的key判等都相等时可以采用额外的Index来保持相对的原始序。而且有意思的是,Array.Sort()函数具体使用的排序方法是根据数据规模发生改变的
-如果数据量小于等于16个,则采用插入排序 -如果需要排序的数量超过2 * log(N),其中N为输入的排序范围,则采用堆排序 -其余情况均采用快速排序
以上是对常用的标准库排序算法的总结和不同语言的对比,可以根据实际需要和数据量的大小来选择合适的排序算法。
|