【知识点】
虽然我们已经学习了诸如快速排序、桶排序、基数排序、插入排序、选择排序等众多的排序算法,但在算法竞赛中,如需要进行排序,我们一般不会去重复造轮子,即去实现某种排序算法后再使用,而是直接调用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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)