# Optimizing struct sorting algorithm

• 04-07-2011
843
Optimizing struct sorting algorithm
I want to sort 4 players according to their scores (player[0].win through player[3].win) and then display the sorted list as such: A B C D.

What would be an efficient algorithm to solve this problem? The one I'm using is very tedious and takes a lot of space. Here's a quarter of the code snippet:

Code:

*pointer =  max(max(player[0].pts, player[1].pts),
max(player[2].pts, player[3].pts));

if (*pointer == player[0].pts) {
pos1 = 'A';
*pointer = max( player[1].pts,
max(player[2].pts, player[3].pts));

if (*pointer == player[1].pts) {
pos2 = 'B';
*pointer = max( player[2].pts, player[3].pts);

if (*pointer == player[2].pts) {
pos3 = 'C';
pos4 = 'D';
}

else {
pos3 = 'D';
pos4 = 'C';
};
}

else if (*pointer == player[2].pts) {
pos2 = 'C';
*pointer = max( player[1].pts, player[3].pts);

if (*pointer == player[1].pts) {
pos3 = 'B';
pos4 = 'D';
}

else {
pos3 = 'D';
pos4 = 'B';
};
}

else if (*pointer == player[3].pts) {
pos2 = 'D';
*pointer = max( player[1].pts, player[2].pts);

if (*pointer == player[1].pts) {
pos3 = 'B';
pos4 = 'C';
}

else {
pos3 = 'C';
pos4 = 'B';
};
}
}

• 04-07-2011
Salem
There are standard functions available in C and C++ for sorting an array of things.

For example
qsort(3): sorts array - Linux man page

All you need to do is write a function which takes two "pointers to elements" which can return a result indicating what "order" the two elements should be in.

There are plenty of examples of using qsort on this board (I've posted plenty).
• 04-08-2011
laserlight
Use std::sort with the same predicate that you wrote for std::max_element based on my example. (But I notice that you're not using max_element...)
• 04-08-2011
843
Thanks for the info. I didn't use max_elements because I figured it would be easier to use max() for finding the 2nd and 3rd element of the array. The max_element seems to be useful only for finding the top value. Well, either that or I'm just having a hard time trying to program it.