排序--2006年华中科技大学计算机保研机试真题
无脸男xm 2019-01-17 10:54:24 冒泡排序的方法:
#include<iostream>
using namespace std;
int main() {
int i,j,n,temp;
while(cin>>n) { //换成这样就ok啦啦啦啦
int *a=new int [n];
for(i=0; i<n; i++)
cin>>a[i]; //error:a[i]写成a[n] cin>>写成cin<<
for(i=0; i<n-1; i++) {
for(j=0; j<n-i-1; j++) {
if(a[j]>a[j+1]) { //error: 应该是a[j+1]
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0; i<n; i++) {
cout<<a[i]<<" ";
}
delete [] a; //???delete array
cout<<endl;
}
return 0;
}
直接调用快排算法:更加快捷
#include<iostream>
#include<algorithm> //使用sort,头文件
using namespace std;
bool cmp(int x,int y)
{
return x<y; //定义排序规则,如果要降序输出,只需改为:x>y
}
int main() {
int n;
while(cin>>n) {
int a[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;
}