I am trying to sort a list from a binary file of players hockey stats. My goal is to use selection sort algorithm to sort the list in a descending order based on number of points in a game where points = goals + assists.
I am using an array of structures where each array is a structure of the players stats.
Here is the structure.
struct Player
{
char name[20];
int goals;
int assists;
int rating;
};
This is what I have in my sort array function so far.
void sortArrays( Player players[], int numPlayers)
int top=0;
int ssf;
int last=numPlayers;
int ptr;
int i = 0;
Player temp;
while (top < last)
{
ptr=top;
ssf=top;
pnts = players[i].goals + players[i].assists;
i++;
}
After this I am stuck.
Here are the steps the function is suppose to perform in broad terms.
Calculate number of points by using the formula points = player[i].goals + player[i].assists
Sort the array of structures in descending order based on number of points.
Swap the different arrays until the list is sorted in a descending order based on greatest amount of points to least.
Do you have to use selection sort? You could use std::sort
instead if you define a custom comparison function:
bool compare_players(Player const& a, Player const& b) {
return (b.goals + b.assists) < (a.goals + a.assists);
}
Then throw your players into a vector
called players
and just
std::sort(players.begin(), players.end(), &compare_players);
This is less code and it's also more efficient (O(n log n)) than implementing a selection sort (O(n^2)).