Search code examples
c#arraysbubble-sort

Sort a string array based on an int array without Array.Sort


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.


Solution

  • 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;
            }
        }
    }