c++ STL sort

排序是应用于数据的最基础的功能之一。这意味着以特定的方式排列数据,可以是增序也可以逆序。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值