无法在C中使用气泡排序对字符数组进行排序
我试图对C中的字符数组进行排序,但它打印出的是相同的数组,而不是排序后的数组无法在C中使用气泡排序对字符数组进行排序,c,arrays,sorting,char,bubble-sort,C,Arrays,Sorting,Char,Bubble Sort,我试图对C中的字符数组进行排序,但它打印出的是相同的数组,而不是排序后的数组 char*P[5] = {"1c", "4h", "3g", "10g"}; total_items = 4; // number of elements in the array. for(int q =1; q<total_items; q++) { for(int k=0; k<total_items-q; k++) { if((int)P[k]>=(int)
char*P[5] = {"1c", "4h", "3g", "10g"};
total_items = 4; // number of elements in the array.
for(int q =1; q<total_items; q++)
{
for(int k=0; k<total_items-q; k++)
{
if((int)P[k]>=(int)P[k+1])
{
temp=P[k];
P[k]=P[k+1];
P[k+1]=temp;
}
}
}
char*P[5]={“1c”、“4h”、“3g”、“10g”};
项目总数=4;//数组中的元素数。
对于(intq=1;q创建您自己的比较函数
像这样:
int cmp(const char *a, const char *b){
int ai, bi;
char ac, bc;
sscanf(a, "%d%c", &ai, &ac);//Separate number and letter
sscanf(b, "%d%c", &bi, &bc);
if(ac > bc)
return 1;
else if(ac < bc)
return -1;
return ai < bi ? -1 : ai > bi;
}
int-cmp(常量字符*a,常量字符*b){
国际ai,bi;
查尔ac,bc;
sscanf(a、%d%c、&ai和&ac);//数字和字母分开
sscanf(b、%d%c、&bi、&bc);
如果(ac>bc)
返回1;
否则如果(acbi;
}
然后将if((int)p[k]>=(int)p[k+1])
替换为if(cmp(p[k],p[k+1])>0
使用strcmp
代替=
(
)@BLUEPIXY:Hi,你能帮我编辑这个吗?我试过使用strcmp,它以相反的顺序打印出整个数组,不知道我在这里哪里出错:\Read@StackOverflow你应该能够根据strcmp的返回值来写条件。@Mahesh:你能编辑我的解决方案并将其作为答案发布吗?Hi,谢谢非常感谢。只是另一个问题,当我尝试使用不同的数组(如{1a1c2a 2f 1d})运行代码时,代码失败了,它输出了2a 1d“whitespace”2f。你知道为什么吗?