下面这个是用冒泡排序,运行错误
#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
char ptr[N][80]={ "how ","are ","you ","i","fine" };
char *p[N];
char *temp;
int i,j;
for(i=0;i<N;i++) p[i]=ptr[i];
for(i=0;i<N-1;i++)
for(j=0;j<N-i;j++)
if(strcmp(p[j],p[j+1])>0)
{
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
}
for(i=0;i<N;i++)
puts(p[i]);
}
下面这个是用选择排序,运行结果却是正确的
#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
char ptr[N][80]={ "how ","are ","you ","i","fine" };
char *p[N];
char *temp;
int i,j;
for(i=0;i<N;i++) p[i]=ptr[i];
for(i=0;i<N-1;i++)
for(j=i+1;j<N;j++)
if(strcmp(p[i],p[j])>0)
{
temp=p[j];
p[j]=p[i];
p[i]=temp;
}
for(i=0;i<N;i++)
puts(p[i]);
}
下面这个没有用指针,直接改变原字符串数组,是用冒泡排序
也是正确的
#include<stdio.h>
#include<string.h>
#define N 5
int main()
{
char ptr[N][80]={ "how ","are ","you ","i","fine" };
char temp[80];
int i,j;
for(i=0;i<N-1;i++)
for(j=0;j<N-i;j++)
if(strcmp(ptr[j],ptr[j+1])>0)
{
strcpy(temp,ptr[j]);
strcpy(ptr[j],ptr[j+1]);
strcpy(ptr[j+1],temp);
}
for(i=0;i<N;i++)
puts(ptr[i]);
}
求解答,万分感谢!