簡體   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