There is an array of odd and even numbers. Now, sort them in such a way that the top portion of the array contains odd numbers, bottom portion contains even numbers. The odd numbers are to be sorted in descending order and the even numbers in ascending order.
If the array is {1,4,5,2,3,6,7} the result would be {7,5,3,1,2,4,6} but I am getting {2,4,6,7,5,3,1}. Any pointers as to where I am going wrong?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lessthan(const void *a, const void *b)
{
if(*(int *)a%2==1)
{
if(*(int *)b%2==0)
{
return 1;
}
else if(*(int *)b%2==1)
{
if(*(int *)a < *(int *)b)
{
return 1;
}
else if(*(int *)a > *(int *)b)
{
return -1;
}
}
}
else if(*(int *)a%2==0)
{
if(*(int *)b%2==1)
{
return -1;
}
else if(*(int *)b%2==0)
{
if(*(int *)a < *(int *)b)
{
return -1;
}
else if(*(int *)a > *(int *)b)
{
return 1;
}
}
}
}
int main(void)
{
int n = 0;
int values[] = {4,1,5,2,3,6,7};
int len = 7;
qsort(values, len, sizeof(int), lessthan);
for(n=0;n<len;n++)
{
printf("%d ", values[n]);
}
return 0;
}
output:
2 4 6 7 5 3 1