繁体   English   中英

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

[英]Sort a string array based on an int array without Array.Sort

我需要根据整数数组对字符串数组进行排序。

我有这个来排序我的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;
            }
        }
    }

此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]);
}

对于我的作业,我需要显示名称和其得分最高的得分。

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

任何提示或帮助将不胜感激。

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

当交换int数组中的项目时,还交换字符串数组中的相应项目。 这样,值便会彼此跟随,并且名称和分数保持同步。

请注意,排序算法是气泡排序的低效版本。 如果内部循环运行中没有交换,则对数组进行排序,您可以退出外部循环。

暂无
暂无

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

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