1.对int类型数组排序(只需用sort就行了 ,不用cmp函数)
#include<stdio.h>
#include<algorithm>
using namespace std;
# define N 110000
int a[N];
int main ()
{
int i,t;
scanf("%d",&t);
while(t--)
{
for(i=0;i<10;i++)
scanf("%d",&a[i]);
sort(a,a+10);
for(i=0;i<10;i++)
printf("%d ",a[i]);
printf("\n");
}
}
2.对char类型数组排序
需要定义一个cmp函数,其他的和int类型的基本一样。
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
# define N 110000
char a[N];
int cmp(char a,char b)
{
return a<b;
}
int main ()
{
int len;
while(1)
{
scanf("%s",a);
len=strlen(a);
sort(a,a+len,cmp);
printf("%s\n",a);
}
return 0;
}
3.对字符串进行排序
(1)需要借用结构体
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
# define N 110000
struct A{
char a[N];
};
int cmp(A s1,A s2)
{
return strcmp(s1.a,s2.a)<0;//注意return 的返回值 ,对字符串处理时需要调用strcmp
}
int main ()
{
A b[3];
scanf("%s%s%s",b[0].a,b[1].a,b[2].a);
sort(b,b+3,cmp);
printf("%s",b[0].a);
return 0;
}
结构体多级排序:
#include<stdio.h>
#include<algorithm>
using namespace std;
struct A{
int a,b;//a是语文成绩,b是数学成绩,c是人名
char c[20];
};
int cmp(A s1,A s2)
{
if(s1.a==s2.a)
{
if(s1.b==s2.b)
{
return strcmp(s1.c,s2.c)<0;
}
return s1.b<s2.b;
}
return s1.a<s2.a;
}
#include<stdio.h>
#include<algorithm>
using namespace std;
# define N 110000
int cmp(const void *s1, const void *s2)
{
return strcmp((char *)s1,(char *)s2);
}
int main ()
{
char a[3][20];
scanf("%s%s%s",a[0],a[1],a[2]);
qsort(a,3,sizeof(a[0]),cmp);
printf("%s",a[0]);
return 0;
}
(3)冒泡法排字符串 用strcmp和strcpy
#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
# define N 10000
char a[N][20];
char b[20];
int main ()
{
int i,j;
for(i=0;i<5;i++)
scanf("%s",a[i]);
for(j=0;j<4;j++)
{
for(i=0;i<4-j;i++)
{
if(strcmp((a[i]),(a[i+1]))>0)
{
strcpy(b,a[i]);
strcpy(a[i],a[i+1]);
strcpy(a[i+1],b);
}
}
}
for(i=0;i<5;i++)
{
printf("%s\n",a[i]);
}
return 0;
}
(4)借用string类 ,用sort进行排序:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
string str[20];
int main (){
for(int i = 1; i <= 3; ++i)
cin>>str[i];
sort(str + 1, str + 3 + 1);
for(int i = 1; i <= 3; ++i)
cout << str[i] << endl;
return 0;
}
都是以前自己尝试总结的,和现在的代码风格都不一样了。
希望大神指点