Painguy
Painguy

Reputation: 567

Bubble sort array of pointers

So I'm trying to sort an array of pointers as seen below. The problem I have is that the array contains one null element. I have to dereference all the elements except NULL other wise i get an error of course, but this causes my sort to not properly sort any elements after NULL appears. I can create a specific exception for a NULL case, but is there anyway to avoid this, and treat NULL at 0 while I still dereference everything else? right now i tell the sort to ignore NULL. This is just a place holder as I have been unable to find a solution to my problem.

#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;
            }
        }
    }
}

Upvotes: 0

Views: 2059

Answers (4)

JustinDanielson
JustinDanielson

Reputation: 3185

Change this

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

To

//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){

Add int x,y; to the top of the function as well.

edit: added dereferencing pointers. lol

Upvotes: 2

Kaz
Kaz

Reputation: 58598

    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;
        }
    }

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754060

Should the NULL be sorted first or last? Decide. The decision controls your comparison code:

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

Where:

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;
}

This sorts NULL before any valid value.


You have another problem:

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

vs

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

These are not the same signature; your code should not be compiling.

Upvotes: 1

cloudygoose
cloudygoose

Reputation: 668

How about you let

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

Then you first find that NULL in the array, and set it to be ptNull.
And then you can sort as if there is no NULL in the array.

Upvotes: 1

Related Questions