作为一个大一计算机系学生,上学期自学C语言,学了冒泡排序感觉好厉害的样子。。。直到我发现了C++里的sort函数。
排序函数sort对给定区间所有元素进行排序。头文件:#include <algorithm>
语法描述为:sort(begin,end),表示一个范围,for example:
int a[n],sort(a,a+n)//将是把数组a按升序排序
这个函数会使oj效率提高好多。举个例子:HDU1040一道水题
As Easy As A+B
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 70504 Accepted Submission(s): 29990
Problem Description
These days, I am thinking about a question, how can I get a problem as easy as A+B? It is fairly difficulty to do such a thing. Of course, I got it after many waking nights.
Give you some integers, your task is to sort these number ascending (升序).
You should know how easy the problem is now!
Good luck!
Give you some integers, your task is to sort these number ascending (升序).
You should know how easy the problem is now!
Good luck!
Input
Input contains multiple test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each test case contains an integer N (1<=N<=1000 the number of integers to be sorted) and then N integers follow in the same line.
It is guarantied that all integers are in the range of 32-int.
It is guarantied that all integers are in the range of 32-int.
Output
For each case, print the sorting result, and one line one case.
Sample Input
2 3 2 1 3 9 1 4 7 2 5 8 3 6 9
Sample Output
1 2 3 1 2 3 4 5 6 7 8 9
#include<cstdio>
#include<iostream>、
using namespace std;
int main()
{
int i,j,n,k,t;
int a[1005];
scanf("%d",&n);
while(n--) {
scanf("%d",&k);
for(i=0;i<k; i++)
scanf("%d",&a[i]);
for(i=0;i<k; i++) {
for(j=0; j<k;j++) {
if(a[i]<a[j]) {
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
for(i=0;i<k;i++) {
if(i!=k-1)
printf("%d ",a[i]);
else
printf("%d\n",a[i]);
}
}
return 0;
}
还好这个题的数据要求比较小,如果很大的话,冒泡排序很可能会超时。
下面是神奇的sort函数:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
int i,j;
int a[1000];
scanf("%d",&n);
while(n--)
{
scanf("%d",&i);
for(j=0;j<i;j++)
{
scanf("%d",&a[j]);
}
sort(a,a+i);
for(j=0;j<i;j++)
{
if(j!=i-1)
printf("%d ",a[j]);
else
printf("%d\n",a[j]);
}
}
return 0;
}
代码简单了许多有木有!!!
降序的话:自己编写一个compare函数来实现,接着调用三个参数的sort:sort(begin,end,compare)
自己编写compare函数:
bool compare(int a,int b)
{
return a<b; //升序排列,如果改为return a>b,则为降序
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for(i=0;i<20;i++)
cout<<a[i]<<endl;
sort(a,a+20,compare);
for(i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
学无止境!