排序-Sort函数(一)
Sort函数
Sort函数用于对给定区间所有元素进行排序
头文件为:#include < algorithm >
万能头文件:#include<bits/stdc++.h>
使用sort()在具体实现中规避了经典快速排序可能出现的、会导致实际复杂度退化到o(n²)的极端情况。它根据具体情况使用不同排序方法,效率极高。 sort函数基本格式: sort(首元素地址,尾元素地址的下一个地址,比较函数); 说明:排序方法可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。 举例:下面就具体使用sort()函数结合对数组里的十个数进行排序做一个说明。 sort函数没有第三个参数。
1. 交叉排序
看着题目写你的思路:n个数,数组num[10001],规定两个范围l1到r1,l2到r2。
先排l1到r1从小到大,再排l2到r2从大到小。
数组的排序在进行一次之后,并不是想象中的数字改变下标,而是下标改变了数字。所以我们可以知道这道题的题例顺序是:
输入:6 1 3 2 4
8 3 1 6 9 2
第一次改变:1 3 8 6 9 2
第二次改变:1 8 6 3 9 2
输出:1 8 6 3 9 2
解决了第一点,我们可以写出以下代码:
#include<bits/stdc++.h>
using namespace std;
int num[10001];
int main()
{
int N,l1,r1,l2,r2;
cin>>N>>l1>>r1>>l2>>r2;
for(int i=0;i<N;i++)
cin>>num[i];
sort(num+l1-1,num+r1);
sort(num+l2-1,num+r2);
for(int i=0;i<N;i++)
cout<<num[i]<<" ";
return 0;
}
注意一下,“ sort(num+l1-1,num+r1);sort(num+l2-1,num+r2);”中“num+1”是因为sort的数组默认开始值是0,因此num不仅要加上r1,还要加上1。
如何将sort改为从大到小
1.应用代码greater()
2.调用函数
bool cmp(int a,int b)
{
return a>b;
}
我们在将第二次排序改为从大到小,就完成啦!(* ^ ▽ ^ *)
总代码:
#include<bits/stdc++.h>
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
int num[10001];
int main()
{
int N,l1,r1,l2,r2;
cin>>N>>l1>>r1>>l2>>r2;
for(int i=0;i<N;i++)
cin>>num[i];
sort(num+l1-1,num+r1);
sort(num+l2-1,num+r2,cmp);
for(int i=0;i<N;i++)
{
if(i!=N-1)
cout<<num[i]<<" ";
else
cout<<num[i]<<endl;
}
return 0;
}
//Tangwan-jeff
练习1-小信的随机数
正确答案:(答案仅供参考,方法各有异同)
#include<bits/stdc++.h>
using namespace std;
int main()
{
set<int> ra;
int T;
int buf;
cin>>T;
while(T--)
{
cin>>buf;
ra.insert(buf);
}
cout<<ra.size()<<endl;
set<int>::iterator it;
int n=0;
for(it=ra.begin();it!=ra.end();it++)
{
++n;
cout<<*it;
if(n!=ra.size())cout<<" ";
}
return 0;
}
//Tangwan-jeff
2.身高排序
stable_sort可以使在排序时两个相同的数不交换顺序
bool cmp(const node &a,const node &b)
{
return a.h<b.h;
} 相对于
bool cmp(int a,int b)
{
return a>b;
}
来讲,前者与原本的sort的功能是一样的,只是保障了范围内(放在哪儿的就是哪个范围)不会再发生改变,比如各种的特殊情况
总代码:(结构体)
#include<bits/stdc++.h>
using namespace std;
struct node//以字符串/指针/结构体 来定义更加的方便
{
int h;
int i;
};
bool cmp(const node &a,const node &b) //从小到大
{
return a.h<b.h;
}
int main()
{
int n;
cin>>n;
node arr[n+5];
for(int i=1;i<=n;i++)
{
int x;
cin>>x;
arr[i].h=x;
arr[i].i=i;
}
stable_sort(arr+1,arr+1+n,cmp);/*题中有要求“如果两个同学身高相同,那么这两个同学的相对顺序不应该发生变化”
而stable-sort则是在sort的基础上使得两个相等的数不交换位置 */
for(int i=1;i<n;i++)
cout<<arr[i].i<<" ";
cout<<arr[n].i;
return 0;
}
//Tangwan-jeff
总代码:(数组)
#include<bits/stdc++.h>
using namespace std;
struct xs
{
int bh,sg;
};
bool cmp(xs x,xs y)
{
return x.sg<y.sg;
}
int main()
{
int n;
xs a[1005];
cin>>n;
for (int i=1;i<=n;i++)
{
a[i].bh=i;
scanf("%d",&a[i].sg);
}
stable_sort(a+1,a+n+1,cmp);
for (int i=1;i<n;i++)
printf("%d ",a[i].bh);
printf("%d",a[n].bh);
return 0;
}
//Tangwan-jeff
练习2-平均分排序
正确答案:
#include<bits/stdc++.h>
using namespace std;
double a[101];
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]<<endl;
return 0;
}