算法初步——排序——sort函数

1. 如何使用 sort 排序

加上: "#include <algorithm>" 和 "using namespace std;"

sort ( 首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填) );

#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
	int a[6] = {9, 4, 2, 5, 6, -1};
	// 对 a[0]~a[3] 排序
	sort(a, a+4);
	for(int i = 0; i < 6; i++){
		printf("%d ", a[i]);
	}
	printf("\n");
	// 对 a[0]~a[5] 排序
	sort(a, a+6);
	for(int i = 0; i < 6; i++){
		printf("%d ", a[i]);
	}
	return 0;
}

2. 如何实现比较函数 cmp

(1)基本数据类型数组的排序

若比较函数不填,则默认按照从小到大的顺序排序

#include <stdio.h>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
	return a > b;
}
int main(){
	int a[4] = {3, 1, 4, 2};
	// 不加 cmp 函数,默认从小到大排序
	sort(a, a+4);
	for(int i = 0; i < 4; i++){
		printf("%d ", a[i]);
	}
	printf("\n");
	// 加 cmp 函数,从大到小排序
	sort(a, a+4, cmp);
	for(int i = 0; i < 4; i++){
		printf("%d ", a[i]);
	}
	return 0;
}

(2)结构体数组的排序

#include <stdio.h>
#include <algorithm>
using namespace std;
struct node{
	int x, y;
}ssd[10];
// 一级排序
bool cmp1(node a, node b){
	return a.x > b.x;
}
// 二级排序
bool cmp2(node a, node b){
    if(a.x != b.x)
        return a.x > b.x;
    else
        return a.y < b.y;
}
int main(){
	ssd[0].x = 2;
	ssd[0].y = 2;
	ssd[1].x = 1;
	ssd[1].y = 3;
	ssd[2].x = 3;
	ssd[2].y = 1;
    // 一级排序
	sort(ssd, ssd+3, cmp1);
	for(int i = 0; i < 3; i++){
		printf("%d %d\n", ssd[i].x, ssd[i].y);
	}
    // 二级排序
    sort(ssd, ssd+3, cmp2);
	for(int i = 0; i < 3; i++){
		printf("%d %d\n", ssd[i].x, ssd[i].y);
	}
	return 0;
}

(3)容器的排序

只有 vector、string、deque 可以使用 sort

vector:

#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b){
	return a > b;
}
int main(){
	vector<int> vi;
	vi.push_back(3);
	vi.push_back(1);
	vi.push_back(2);
	sort(vi.begin(), vi.end(), cmp);
	for(int i = 0; i < 3; i++){
		printf("%d ", vi[i]);
	}
	return 0;
}

string:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
	string str[3] = {"bbbb", "cc", "aaa"};
	sort(str, str+3);
	for(int i = 0; i < 3; i++){
		cout << str[i] << endl;
	}
	return 0;
}

如果 按 字符串长度从小到大 排序:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string str1, string str2){
	return str1.length() < str2.length();
}
int main(){
	string str[3] = {"bbbb", "cc", "aaa"};
	sort(str, str+3, cmp);
	for(int i = 0; i < 3; i++){
		cout << str[i] << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/gsj9086/article/details/86406079
今日推荐