分类
Level4

sort()函数

sort()函数 是C++提供的一种排序方法之一,它使用的排序方法是类似于快排的方法(既有快速排序又有与其它排序方法的结合),时间复杂度为  ,执行效率很高!

sort函数包含在头文件为<algorithm> 。

sort()函数为非稳定排序,稳定排序可以用stable_sort()函数。

sort函数使用模板

#include <algorithm>
sort(start, end, 排序方法)

sort函数有三个参数:

  • 第一个是要排序的起始地址。
  • 第二个是要排序的结束地址。
  • 第三个参数是排序的方法,默认的排序方法是从小到大排序。

sort()函数的强大之处是在它的第三个参数,排序方法,就是说可以任意的设定自己的规则,使排序对象按照自己指定的规则进行排序。特别是在对字符串数组进行比较时用处很大,可以很轻松的解决一些字符串排序的算法问题。

  • 「特别强调:排序范围是[a, b), 闭区间 开区间, – 包含a 不包含b」
  • 「特别强调:C++里两个字符串字节进行比较时,是把字符串的每个字符从首端开始进行按照ASCII值的大小进行比较,如果相同,依次往下比.」

示例 从小到大排列


#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

int a[7] = {123, 456, 32, 3553, 234, 342, 234};

int main(){
	sort(a, a+7);
	for(int i=0; i < 7; i++) {
		printf("%d ", a[i]);
	}

	return 0;
 }


示例 容器

vector <int> a;sort(a.begin(), a.end());

示例 比较函数 从大到小排列

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int a[7] = {123, 456, 32, 3553, 234, 342, 234};
bool compare(int a, int b){    //大的排前面
    return a > b;
}
int main(){	
    sort(a, a+7, compare);  //第三个参数是函数名字	
    for(int i=0; i < 7; i++) {
	printf("%d ", a[i]);	
    }
    return 0; 
}

结构体比较 比较函数

struct Node {
    int len;
    int last;
} node[100008];
bool compare(Node n1, Node n2){  //结构体比较函数
    if (n1.last == n2.last){
	return n1.len > n2.len;
    }	
    return n1.last < n2.last;
}

//应用sort(node, node+n, compare);

< 重载

struct Node {
	int len;
	int last;
	bool operator( const node &b ) const {
		if (last == b.last){
			return len > b.len;
                }
		return last < b.last;	
        }
};
Node node[200];
sort(node+1, node+100);