算法竞赛中,sort()函数的常见用法。

【知识点】
虽然我们已经学习了诸如快速排序、桶排序、基数排序、插入排序、选择排序等众多的排序算法,但在算法竞赛中,如需要进行排序,我们一般
不会去重复造轮子,即去实现某种排序算法后再使用,而是直接调用sort()函数。
而在具体的排序数据中,又有
结构体数据及非结构体数据。下面分别阐述。

【非结构体数据利用sort()函数进行
递增排序】
● 数组a[]元素下标从0开始,则调用
sort(a,a+n)进行递增排序。其中,n为数组a[]中元素的个数。

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
int a[maxn];

int main() {
    int n;
    cin>>n;
    for(int i=0; i<n; i++) {
        cin>>a[i];
    }
    
    sort(a,a+n);
    for(int i=0; i<n; i++) {
        cout<<a[i]<<" ";
    }

    return 0;
}


/*
in:
7
6 12 9 66 7 8 9

out:
6 7 8 9 9 12 66
*/

● 数组a[]元素下标从1开始,则调用sort(a+1,a+1+n)进行递增排序。其中,n为数组a[]中元素的个数。

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
int a[maxn];

int main() {
    int n;
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>a[i];
    }
    
    sort(a+1,a+1+n);
    for(int i=1; i<=n; i++) {
        cout<<a[i]<<" ";
    }

    return 0;
}


/*
in:
7
6 12 9 66 7 8 9

out:
6 7 8 9 9 12 66
*/

【非结构体数据利用sort()函数进行递减排序】
● 数组a[]元素下标从0开始,则调用
sort(a,a+n,cmp)进行递减排序。其中,n为数组a[]中元素的个数。cmp为下面代码中自定义的实现递减排序的函数名。

int cmp(int a,int b){ //递减排序 
    return a>b;
    }

完整代码如下:

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
int a[maxn];

int cmp(int a,int b){ //递减排序 
    return a>b;
    }

int main() {
    int n;
    cin>>n;
    for(int i=0; i<n; i++) {
        cin>>a[i];
    }
    
    sort(a,a+n,cmp);
    for(int i=0; i<n; i++) {
        cout<<a[i]<<" ";
    }

    return 0;
}


/*
in:
7
6 12 9 66 7 8 9

out:
66 12 9 9 8 7 6
*/

● 数组a[]元素下标从1开始,则调用sort(a+1,a+1+n,cmp)进行递减排序。其中,n为数组a[]中元素的个数。cmp为下面代码中自定义的实现递减排序的函数名。

int cmp(int a,int b){ //递减排序 
    return a>b;
    }

完整代码如下:

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
int a[maxn];

int cmp(int a,int b){ //递减排序 
    return a>b;
    }

int main() {
    int n;
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>a[i];
    }
    
    sort(a+1,a+1+n,cmp);
    for(int i=1; i<=n; i++) {
        cout<<a[i]<<" ";
    }

    return 0;
}


/*
in:
7
6 12 9 66 7 8 9

out:
66 12 9 9 8 7 6
*/


【结构体数据利用sort()函数进行递增\递减排序】
● 详见:
https://blog.csdn.net/hnjzsyjyj/article/details/120184972



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/121888419
https://blog.csdn.net/hnjzsyjyj/article/details/124114512
https://blog.csdn.net/hnjzsyjyj/article/details/130045851
https://blog.csdn.net/hnjzsyjyj/article/details/120184972

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值