Original Post
I'm trying to sort an array of units in the following way: -Find the unit in the middle -sort the units from closest (to the middle unit) to furthest. I used were the FindMiddle function finds the place in the array of the middle unit. That part works. For the compare I used: The problem is that it takes 2-3 time of calling qsort for it to work properly. For example, the middle_man should turn to 0 after one call right?! What is the problem? I think that the problem could be connected to the fact that during the qsort the middle_man changes. If so how do I fix it? Thanks a lot
middle_man = FindMiddle();
qsort((void *) &unit, number_of_units, sizeof(struct unit), (compfn)CompareDisMid );
int CompareDisMid(struct unit *elem1, struct unit *elem2)
{
if(abs(elem1->current_step.x-unit[middle_man].current_step.x)+
abs(elem1->current_step.y-unit[middle_man].current_step.y)
<abs(elem2->current_step.x-unit[middle_man].current_step.x)+
abs(elem2->current_step.y-unit[middle_man].current_step.y))
return -1;
else if(abs(elem1->current_step.x-unit[middle_man].current_step.x)+
abs(elem1->current_step.y-unit[middle_man].current_step.y)
> abs(elem2->current_step.x-unit[middle_man].current_step.x)+
abs(elem2->current_step.y-unit[middle_man].current_step.y))
return 1;
else return 0;
}