排序是应用于数据的最基础的功能之一。这意味着以特定的方式排列数据,可以是增序也可以逆序。
sort函数在内部使用IntroSort。更详细地说,它是使用快速排序、堆排序和插入排序依据默认情况下,它使用快速排序,但如果快速排序执行不公平的分区并占用N*logN时间,它将切换到堆排序,当数组大小变得非常小时,它将切换到插入排序。
sort函数原型
sort(startaddress, endaddress) startaddress: 列表起始地址 endaddress: 列表末尾地址
通用类型
// C++ progrma to sort an array
#include <algorithm>
#include <iostream>
using namespace std;
void show(int a[], int array_size)
{
for (int i = 0; i < array_size; ++i)
cout << a[i] << " ";
}
// Driver code
int main()
{
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
// size of the array
int asize = sizeof(a) / sizeof(a[0]);
cout << "The array before sorting is : \n";
// print the array
show(a, asize);
// sort the array
sort(a, a + asize);
cout << "\n\nThe array after sorting is :\n";
// print the array after sorting
show(a, asize);
return 0;
}
输出
The array before sorting is : 1 5 8 9 6 7 3 4 2 0 The array after sorting is : 0 1 2 3 4 5 6 7 8 9
自定义类型
自定义类型需要程序员自己去实现比较函数,比较函数实现的方式有两种:
- 实现操作符比较函数 bool operator<(const MyFav&) const;
- 实现比较函数 bool MyFavCompare(const MyFav& i1, const MyFav& i2);
// C++ progrma to sort an array
#include <algorithm>
#include <iostream>
using namespace std;
struct MyFav {
int x;
int y;
bool operator<(const MyFav& fav) const {
return this->x < fav.x;
}
};
bool MyFavCompare(const MyFav& i1, const MyFav& i2)
{
return (i1.x < i2.x);
}
void showMyFav(MyFav arr[], int lenth) {
for(int i=0; i<lenth; i++) {
cout << arr[i].x << ", " << arr[i].y << endl;
}
}
// Driver code
int main()
{
MyFav myFavArr[] = {{2, 3}, {5, 1}, {3, 4}, {1, 8}};
// size of the array
cout << "The array before sorting is : \n";
// size of the array
int lenth = sizeof(myFavArr) / sizeof(myFavArr[0]);
// print the array
showMyFav(myFavArr, lenth);
// sort the array
// 方式一,使用比较函数
//sort(myFavArr, myFavArr+lenth, MyFavCompare);
// 方式二,struct/class内部实现比较函数
sort(myFavArr, myFavArr+lenth);
cout << "\n\nThe array after sorting is :\n";
// print the array after sorting
showMyFav(myFavArr, lenth);
return 0;
}
输出
The array before sorting is :
2, 3
5, 1
3, 4
1, 8
The array after sorting is :
1, 8
2, 3
3, 4
5, 1