Reputation: 165
I need to sort an array of strings based on the array of ints.
I have this to sort my int array
for (int pass = 0; pass < score.Length - ONE; pass++)
{
for (int index = 0; index < score.Length - ONE; index++)
{
if (score[index] > score[index + ONE])
{
int temp = score[index];
score[index] = score[index + ONE];
score[index + 1] = temp;
}
}
}
This int and name array were obtained by
Console.Write("Enter in a name and score: ", i);
userInput = Console.ReadLine();
if (userInput != "")
{
parsedInput = userInput.Split();
name[i] = parsedInput[ZERO];
score[i] = int.Parse(parsedInput[ONE]);
}
For my assignment I need to display the name and their scores organized by the highest score.
I know I could use Array.Sort(score, name) to achieve this but the assignment wants me to not use any of the built in sorting algorithms in the .net library, which is assume Array.Sort would be.
Any tips or help would be greatly appreciated.
Upvotes: 0
Views: 675
Reputation: 700612
When you swap the items in the int array, also swap the corresponding items in the string array. That way the values follow each other, and the name and score remain in sync.
Note that the sorting algorithm is an inefficient version of bubble sort. If there are no swaps in a run of the inner loop, the array is sorted and you can exit out of the outer loop.
Upvotes: 0
Reputation: 472
You need to rearrange name
when you are sorting score
so that they are consistent.
for (int pass = 0; pass < score.Length - ONE; pass++)
{
for (int index = 0; index < score.Length - ONE; index++)
{
if (score[index] > score[index + ONE])
{
int temp = score[index];
score[index] = score[index + ONE];
score[index + 1] = temp;
string temp2 = name[index];
name[index] = name[index + ONE];
name[index + 1] = temp2;
}
}
}
Upvotes: 1