C语言给字符串冒泡排序

#define N 5
#define M 10
#include<stdio.h>
#include<string.h>
int main()
{
	int i,j;
	char *t=NULL;
	char str[N][M]={"monitor","landscape","paddle","partition","current"};
	for(i=0;i<N;i++)
		for(j=0;j<N;j++){ 
			if(strcmp(str[j],str[j+1])>0){
				t=str[j];
				strcpy(str[j],str[j+1]);
				strcpy(str[j+1],t);
			}
		} 
		
	for(i=0;i<N;i++)
		puts(str[i]);
	return(0);
}

请问怎么用指针将字符串交换顺序?

#define N 5
#define M 10
#include<stdio.h>
#include<string.h>
int main()
{
	int i,j;
	char *t=NULL;
	char *str[N]={"monitor","landscape","paddle","partition","current"};
	for(i=0;i<N-1;i++)
		for(j=0;j<N-i-1;j++){
			if(strcmp(str[j],str[j+1])>0){
				t=str[j];
				str[j] = str[j+1];
				str[j+1] = t;
			}
		}

	for(i=0;i<N;i++)
		puts(str[i]);
	return(0);
}

 

你t是指针,数组元素也要是指针才能交换地址,这样只交换指针指向的地址,而字符串在内存中的数据不动,效率很高。

 

如果用strcpy();复制字符串就需要为t分配一个单独的空间

#define N 5
#define M 10
#include<stdio.h>
#include<string.h>
int main()
{
	int i,j;
	char t[M];
	char str[N][M]={"monitor","landscape","paddle","partition","current"};
	for(i=0;i<N-1;i++)
		for(j=0;j<N-i-1;j++){
			if(strcmp(str[j],str[j+1])>0){
				strcpy(t,str[j]);
				strcpy(str[j],str[j+1]);
				strcpy(str[j+1],t);
			}
		}

	for(i=0;i<N;i++)
		puts(str[i]);
	return(0);
}

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632