1

I am trying to write a simple program to find the median of an array. To do that first I tried to use qsort to put my values in order but I can't quite get it to work. I believe it has something to do with my function parameter and pointers.

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


int cmpfunc (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
}

int median(const int* array)
{
    double median;
    int length =0;
    while(array[length])
        length++;

    qsort(*array, length, sizeof(int), cmpfunc);

    if(length %2 ==0)
    {
        median=(array[length/2] + array[(length/2)+1])/2;
    }
    else
    {
        median = array[(length +1/2)];
    }
    return median;
}

int main ()
{
    int array [] = {5, 3, 2, 7, 9};
    printf( "%f", median(array));
}
mantal
  • 879
  • 1
  • 19
  • 34
user2891051
  • 47
  • 3
  • 9

2 Answers2

1

Beside that you are getting wrong value for length with snippet

 while(array[length])  // Array is not ended with zero
    length++;          // Length would get some unexpected value

you need to return double from function median and it also need one more parameter for length.

double median(int* array, const int length){...}  
//            ^Removed const qualifier and added an extra parameter for array size  

Call median as

double result = median(array, sizeof(array)/sizeof(array[0]))
haccks
  • 97,141
  • 23
  • 153
  • 244
1

From the qsort documentation:

void qsort(void *base, size_t nmemb, size_t size,
           int (*compar)(const void *, const void *));

The qsort() function sorts an array with nmemb elements of size size. The base argument points to the start of the array.

First you need to get the length right; second, in your original call to qsort you used qsort(*array...) which is not what you want. Just use qsort(array...).

It is also useful when writing these small tests to view the actual data; you can either use a debugger, or just print out the contents of your array.

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


int cmpfunc(const void *a, const void *b)
{
    return (*(int *) a - *(int *) b);
}


void printArray(int *array, int length)
{
    int i;
    for (i = 0; i < length; i++) {
        printf("%d ", array[i]);
    }
    printf("\n");
}


int median(int *array, int length)
{
    double median;

    printArray(array, length);
    qsort(array, length, sizeof(int), cmpfunc);
    printArray(array, length);

    if (length % 2 == 0) {
        median = (array[length / 2] + array[(length / 2) + 1]) / 2;
    } else {
        median = array[(length + 1 / 2)];
    }
    return median;    
}

int main()
{
    int array[] = { 5, 3, 2, 7, 9 };
    printf("%d\n", median(array, sizeof(array) / sizeof(array[0])));
    return 0;
}
Leonardo Herrera
  • 7,932
  • 4
  • 36
  • 61