冒泡在C中使用空值排序数组

时间:2015-01-20 13:22:17

标签: c arrays sorting bubble-sort

我试图在C中间创建一个带空值的冒泡排序。
当数组以某种方式排序时,代码工作正常,因此空值位于数组的末尾(hense" continue" condition工作)。

我的数组如下所示:[John,David,NULL,Grace,NULL,NULL] 我运行这个功能:

void SortContacts(char * people[]) {
    int i,j;
    char *tempswap;
    for (i=0; i<storage-1; i++) {
        for (j=0; j<storage-i-1; j++) {
                if (people[j+1]==NULL) {
                    continue;
                }
            if (strcmp(people[j],people[j+1]) > 0) {
                tempswap = people[j];
                people[j] = people[j+1];
                people[j+1] = tempswap;
            }
        }
    }
}

当在数组中间执行NULL时,exe崩溃。

3 个答案:

答案 0 :(得分:6)

您不能strcmp NULL值。虽然您正在防范strcmp people[j+1] NULL people[j],但您不会检查strcmp

尝试以下操作(未经测试),它只提供一个NULL函数,用于处理int strcmpwithnull(const char *a, const char *b) { return strcmp(a?a:"", b?b:""); } void SortContacts(char * people[]) { int i,j; char *tempswap; for (i=0; i<storage-1; i++) { for (j=0; j<storage-i-1; j++) { if (strcmpwithnull(people[j],people[j+1]) > 0) { tempswap = people[j]; people[j] = people[j+1]; people[j+1] = tempswap; } } } } 之类的“”。

NULL

如果您希望int strcmpwithnull(const char *a, const char *b) { if (a == b) return 0; /* handles 2 NULLs and two strings at the same location */ else if (!a) return 1; else if (!b) return -1; else return strcmp(a, b); } 被视为更大而不是其他任何字符串,请尝试(再次未经测试):

return 1

如果您希望它们小于任何其他字符串(包括空字符串),请交换return -1和{{1}}。

答案 1 :(得分:0)

这是问题

            if (people[j+1]==NULL) 
            {
                continue;
            }

您需要同时检查jj+1 还要考虑如果数组头部有NULL怎么办?或者你有2个NULLs一个接一个

因此,您还需要检查j j+1

您还应该检查j不是null

答案 2 :(得分:0)

您希望最终得到数组右侧的空值。这可以通过使null严格大于任何字符串来实现。您必须将其编码为比较函数。

int cmp(const char *x, const char *y)
{   if(x == 0) return 1;
    if(y == 0) return -1;
    return strcmp(x, y);
}