Reputation: 11
Hi guys having some trouble sorting a multidimensional array containing the scores for different users in the leaderboard form of a game I am making. I have tried to sort the scores for each user in descending order using temporary variables and then output this with no success. Any help would be much appreciated thanks. I should add that I have only recently started coding and have to do this project as part of my work for school so I am aware that it may not be very efficient and seem very novice.
Here is my method for sorting
( [i, 2] is the score value stored as a string )
private void sortScore(string[,] sort)
{
bool didSwap;
do
{
didSwap = false;
for (int i = 0; i < userNumber; i++)
{
if (i < (userNumber-1))
{
if (Convert.ToInt32(sort[i, 2]) > Convert.ToInt32(sort[i + 1, 2]))
{
string temp = sort[i + 1, 2];
sort[i + 1, 2] = sort[i, 2];
sort[i, 2] = temp;
}
}
}
} while (didSwap);
for (int j = 0; j < userNumber; j++)
{
rtbScoreboard.AppendText("Name: " + sort[j, 0] + "\t" + "Score: " + sort[j, 2] + Environment.NewLine);
}
}
Upvotes: 1
Views: 87
Reputation: 45096
You fail to set didSwap to true
bool didSwap;
do
{
didSwap = false;
for (int i = 0; i < userNumber-1; i++)
{
if (Convert.ToInt32(sort[i, 2]) > Convert.ToInt32(sort[i + 1, 2]))
{
string temp = sort[i + 1, 2];
sort[i + 1, 2] = sort[i, 2];
sort[i, 2] = temp;
didSwap = true;
}
}
} while (didSwap);
Upvotes: 0
Reputation: 20764
You can use LINQ!
var sortedScores = Enumerable.Range(0, sort.GetLength(0)) //number of items
.Select(x => new
{
Name = sort[x, 0],
Score = Convert.ToInt32(sort[x, 2])
}) //converting to a meaningful structure
.OrderByDescending(x => x.Score) //sort in descending order by score
.ToList();
//building output, I don't know what is userNumber, It is a global variable
// that might store number of players to show in score board.
for (int j = 0; j < userNumber; j++)
{
rtbScoreboard.AppendText("Name: " + sortedScores[j].Name + "\t" + "Score: " + sortedScores[j].Score + Environment.NewLine);
}
You should not store data like that. Using a multidimensional array to store names and score is not a good idea. Try defining a class like Player
which has Properties for storing data like Name
and Score
. Then store instances of Player
s in a list.
Upvotes: 1