Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在C中使用气泡排序对字符数组进行排序_C_Arrays_Sorting_Char_Bubble Sort - Fatal编程技术网

无法在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)

我试图对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)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。你知道为什么吗?