字符串数组排序(指针数组)
Description
输入三个字符串,按由小到大的顺序输出,字符串长度小于1000
Input
3行字符串
Output
按照从小到大输出成3行
Sample Input
cde
afg
abc
Sample Output
abc
afg
cde
具体代码如下:
#include<stdio.h>
#include<string.h>
#define N 3
void sort(char *pc[N],int n);
int main()
{
char a[N][100],*p[N]; //此处声明了一个指针数组
int i,j;
for(i=0;i<N;i++)
p[i]=a[i]; //让指针指向a[](行地址)
for(i=0;i<N;i++)
scanf("%s",p[i]);
//scanf("%s",a[i]));
//scanf("%s",*(p+i));
sort(p,N);
for(i=0;i<N;i++)
printf("%s\n",p[i]);
return 0;
}
void sort(char *pc[N],int n)
{
int i=0,j=0,flag;
char t[100];
for(i=0;i<N-1;i++) //此处采用的是改进的冒泡排序法
{
flag=0;
for(j=0;j<N-i-1;j++)
{
if(strcmp(pc[j],pc[j+1])>0)//字典顺序(从小到大)
{
strcpy(t,pc[j]); //注意:strcmp()和strcpy()都是对地址进行操作
strcpy(pc[j],pc[j+1]);
strcpy(pc[j+1],t);
flag=1;
}
}
if(!flag)
break;
}
}