简体   繁体   English

根据没有Array.Sort的int数组对字符串数组进行排序

[英]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 我有这个来排序我的int数组

    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 此int和name数组是通过以下方式获得的

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. 我知道我可以使用Array.Sort(score,name)来实现这一点,但是分配要求我不要使用.net库中的任何内置排序算法(假定Array.Sort是这样)。

Any tips or help would be greatly appreciated. 任何提示或帮助将不胜感激。

You need to rearrange name when you are sorting score so that they are consistent. 在对score排序时,您需要重新排列name ,以使它们一致。

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

When you swap the items in the int array, also swap the corresponding items in the string array. 当交换int数组中的项目时,还交换字符串数组中的相应项目。 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. 如果内部循环运行中没有交换,则对数组进行排序,您可以退出外部循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM