在主函数中输入10个不等长的字符串。用另一个函数对它们按升序排序,然后在主函数中输出这10个已排序的字符串。 希望可以有运行结果图 谢谢!
代码及运行效果图如下:如有帮助,请采纳一下,谢谢。
代码:
#include <stdio.h>
#include <string.h>
void fun(char str[][100],int size)
{
int i ,j;
char temp[50] = {0};
for(i=0; i<size -1; ++i) {
for(j=i+1; j<size ; ++j)
{
if(strcmp(str[i], str[j])>0)
{
strcpy(temp, str[i]);
strcpy(str[i], str[j]);
strcpy(str[j], temp);
}
}
}
}
int main()
{
char buf[10][100] = {0};
int i = 0;
printf("输入10个字符串:\n");
for ( i = 0; i < 10; i++)
{
printf("输入第%d个字符串:\n",i+1);
gets(buf[i]);
}
fun(buf,10);
printf("排序后的字符串:\n");
for ( i = 0; i < 10; i++)
{
printf("%s\n",buf[i]);
}
//getchar();
//getchar();
return 0;
}
运行效果图:
#include
#include
int main(){
void sort(char p[10][100]);
char a[10][100];
printf("请输入十个字符串:");
for(int i=0;i<10;i++){
scanf("%s",(a+i));
}
sort(a);//这个排序算法效率虽低 可是我感觉自己写的的比用库函数(qsort排序函数)好,恩 写的不错
printf("排序后字符串为:\n");
for(int j=0;j<10;j++){
printf("%s\n",*(a+j));
}
return 0;
}
void sort(char p[10][100]){
char temp[100];//这里用指针的话 下面赋值的时候没有指向 就是说指针在使用之前必须初始化
for(int i=0;i<10;i++){
for(int j=0;j<10-i;j++){
if(strcmp(p[j],p[j+1])>0) {
strcpy(temp,p[j]);//在C语言中,数组赋值不能直接赋值 必须用相应的函数
//字符串赋值函数是strcpy 整型赋值函数是memcopy()
strcpy(p[j],p[j+1]);
strcpy(p[j+1],temp);
}
}
}
}