Specifically, I'm having trouble with the "Pancake Glutton" that says I must output each array element, named by index in ascending order:
i.e.
Person 4: ate 10 pancakes
Person 3: ate 7 pancakes
Person 8: ate 4 pancakes
...
Person 5: ate 0 pancakes
I found qsort in the reference guide which works great. I've outputted the list in ascending order, however I cannot seem to produce the person array index for the element that it originally corresponded to. The complexity of the multiple pointers and vague description of the compar function leaves me puzzled.
compar looks like this:
1 2 3 4
int compar (constvoid * a, constvoid * b)
{
return ( *(int*)a - *(int*)b );
}
Where the qsort looks like this:
1 2 3 4 5
int n;
qsort (values, 10, sizeof(int), compar);
for (n=0; n<10; n++)
printf ("%d ",person[n]);
return 0;
I'm having trouble outputting the actual index integer, that the sorted value was stored in.
Here's my code for context, but don't just give me the answer if you can. Explain?
There is a relationship between the person's identifier (which, in this case happens to be his position in the array) and the number of pancakes the person eats. This relationship is shattered when you sort the array.
One possible solution is to make each element of the array a structure which contains both the number of pancakes eaten, and the identifier of the person who ate them.
For instance:
1 2 3 4 5
struct person
{
unsigned identifier ;
unsigned pancakesEaten ;
};
qsort, by the way, is great if you're programming in C. Not so much if you're programming in C++. You might want to check out std::sort.
I've used the suggestions in creating a structure and abandoned the qsort and sort function in exchange for a bubble sort. However, I cannot get the index (represented now by p.id) to print for the correct pancakes eaten (represented by p.pancakes), sorted in order of least to greatest.
Any help? I'm a bit lost in the complexity of my first object.