C程序40 字符串排序

题目:字符串排序。

代码

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define N 3/* 设定要输入的字符串个数,可更改 */

int cmp(char *p1,char *p2) /* 字符串比较函数 */
{
	int i=0;
	while (*(p1+i)==*(p2+i))
	if (*(p1+i++)=='\0') return 0; /* 这里是先判断*(p1+i)=='\0',然后再是i++ */
	return (*(p1+i)-*(p2+i));
}

void sort(char *a[N]) /*排序函数*/
{
	char *temp;
	int i,j;
	for(i=0;i<N-1;i++)/* 选择排序 */
	for(j=i+1;j<N;j++)
	if(cmp(a[i],a[j])<0)
	{
		temp=a[i];/* 交换的是字符串的地址,不是字符串的内容,可更改 */
		a[i]=a[j];
		a[j]=temp;
    }
}
int main(void )
{
		int i;
		char s[N][81],*p[N];/* 设定每个字符串不超过80字节 */
		printf("Please input %d strings one by one:\n",N);
		for(i=0;i<N;i++)
		{gets(s[i]);
		p[i]=s[i];
}
		sort(p);
		printf("The sequence after sort is:\n");
		for(i=0;i<N;i++)
		printf("%s\n",p[i]);
		getch();
		return 0;
} 

运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zm_960810/article/details/86106494
今日推荐