I am looking to implement a very simple function which finds the median of an unsorted array by counting the number of smaller elements and number of larger elements if they are equal in number then the original is considered as median.
I know several algorithm like minHeap and Quick Select, but I am trying to keep things simple as a human would do with a naked eye to simply count larger and smaller numbers. So far I have implemented below function but problem arise when I have duplicate entries in array and also with even and odd array length.
I am new to C programming and need to understand what is going wrong. Below is the code, I have written a function to return random array of variable length to test this function from.
int med(int count, int *array)
{
int i, j, median = -1, smaller = 0, larger = 0;
for(i = 0; i < count; i++)
{
for(j = 0; j < count; j++)
{
//larger++
if(array[i] < array[j] && i!=j)
{
larger++;
}
//Smaller++
if(array[i] >= array[j] && i!=j)
{
smaller++;
}
}
printf("\nFor pivot: %d", array[i]);
if(larger == smaller)
{
printf("\n Smaller: %d", smaller);
printf(" Larger: %d", larger);
median = array[i];
break;
}
else
{
printf("\n Smaller: %d", smaller);
printf(" Larger: %d", larger);
larger = 0;
smaller = 0;
}
}
return median;
}
In some cases like {3,5,0,2,3} my function returns -1 but the actual result should be 3.
EDIT Initially I started with strictly greater or lesser but this condition (larger == smaller) never gets hit when I have duplicate entries thus I considered equal elements as smaller. I am having difficulty handling the equalities