runners3431
runners3431

Reputation: 1455

how does the pointer to the function affect the sort?

This is a simple bubble sort using a function pointer for ascending or descending. I don't understand how the return statement on the ascending/descending function affects the swap.

Maybe I'm reading the return statement wrong on ascending? Does it mean return b if it's less than a? Or does it mean return 0 or 1 if the statement is true? Could use some clarification. Thanks.

void bubble( int work[], const int size, int (*compare)(int a, int b)){
    int pass; /* pass counter */
    int count;

    void swap(int *element1Ptr, int *element2Ptr);

    for ( pass = 1 pass < size; pass++){

    /* loop to control number of comparison per pass */
        if ((*compare)(work[count], work[count+1])){
        swap(&work[count], &work[count + 1]);
     }
  }

 }

void swap ( int *element1Ptr, int *element2Ptr){
   int hold;
   hold = *element1Ptr;
   *element1Ptr = *element2Ptr;
   *element2Ptr = hold;
 }

/* determine whether elements are out of order for an ascending order sort */
 int ascending( int a, int b){
    return b < a;
  }

int descending( int a, int b){
    return b > a
 }

Upvotes: 2

Views: 148

Answers (2)

Dan Fego
Dan Fego

Reputation: 14014

A return statement in C returns the expression given, casted to the return type of the function (if possible). In these cases, b < a and a < b are boolean expressions, which return 1 or 0.

In other terms, it essentially means the following, but more concise (for b < a):

if (b < a) {
    return 1;
}
else {
    return 0;
}

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363697

return b < a;

means: return 1 when b < a and 0 otherwise, i.e. the function returns the value of the boolean expression b < a.

Upvotes: 0

Related Questions