冒泡排序数组的指针

时间:2012-05-07 02:20:52

标签: c arrays pointers null bubble-sort

所以我正在尝试对指针数组进行排序,如下所示。我遇到的问题是该数组包含一个null元素。我必须取消引用除NULL以外的所有元素,否则我当然会得到一个错误,但这会导致我的排序在NULL出现后没有正确排序任何元素。我可以为NULL情况创建一个特定的异常,但无论如何都要避免这种情况,并在0时处理NULL,而我仍然取消引用其他所有内容?现在我告诉排序忽略NULL。这只是一个占位符,因为我无法找到解决问题的方法。

#include <stdio.h>
#include <stdlib.h>

void arr(int ar[], int ele);

int main(){
    int a=0, b=9, x=3, p=2, *ar[]={&a, &b, &x, NULL, &p}, i=0, ele=(sizeof(ar)/sizeof(ar[0]));
    arr(ar, ele);
    printf("\n\n");
    for(;i<ele;i++){
        if(ar[i]==NULL){
            printf("");
        }else{
     printf("%i", *ar[i]);
        }
    }
}

void arr(int *ar[], int ele){
    int i=ele-1, c=0;
    for(;i>0; i--){
        for(;c<i; c++){
            if((ar[c]!=NULL && ar[c+1]!=NULL) && *ar[c]>*ar[c+1]){
                int t=*ar[c+1];
                *ar[c+1]=*ar[c];
                *ar[c]=t;
            }
        }
    }
}

4 个答案:

答案 0 :(得分:2)

更改此

if((ar[c]!=NULL && ar[c+1]!=NULL) && *ar[c]>*ar[c+1]){

//If the pointer is NULL, it will have a value of 0, so the conditional will be false.
x = (ar[c]) ? *ar[c] : 0;
y = (ar[c+1]) ? *ar[c+1] : 0;
if(x > y){

添加int x,y;也是功能的顶部。

编辑:添加解除引用指针。洛尔

答案 1 :(得分:1)

你怎么样

Int *ptNull = new int;
*ptNull = -100(the smallest);

然后你首先在数组中找到NULL,并将其设置为ptNull 然后你可以排序,好像数组中没有NULL。

答案 2 :(得分:1)

NULL应该先排序还是最后排序?决定。决定控制您的比较代码:

if (compare(ar[c], ar[c+1]) < 0)
{
    int t=*ar[c+1];
    *ar[c+1]=*ar[c];
    *ar[c]=t;
}

其中:

static int compare(int const *v1, int const *v2)
{
    if (v1 == NULL)
        return -1;
    if (v2 == NULL)
        return +1;
    if (*v1 < *v2)
        return -1;
    if (*v1 > *v2)
        return +1;
    return 0;
}

这会在任何有效值之前对NULL进行排序。


您还有另一个问题:

void arr(int ar[], int ele);

VS

void arr(int *ar[], int ele){

这些签名不一样;你的代码不应该编译。

答案 3 :(得分:1)

    for(;c<i; c++){
        int left = ar[c] != NULL ? ar[c] : 0;
        int right = ar[c+1] != NULL ? ar[c+1] : 0;

        if (left > right){
            /* swap the pointers, not what they point to! */
            int *t = ar[c+1];
            ar[c+1] = ar[c];
            ar[c] = t;
        }
    }
相关问题