如何对数组进行冒泡排序,但保留值的上下文

How to bubble sort an array, but keep the context of the values

好的,我有一个数组,其中包含 6 个值,表示 6 个月期间(1 月至 6 月)的每个月注册的客户数量。让我们说 CustomerSavedByMonth[i]。现在这些按月排序,所以在索引 0 处有 1 月、2 月 1 日等的客户。

我想使用冒泡排序法对这些进行排序,这样我就可以显示客户最多的月份。然而,当我对它们进行冒泡排序时,它们将失去上下文,因为现在它们没有特定的月份,它们只是有序的。我真的不知道如何更好地解释它,所以我希望这是有道理的。我将如何确保在排序时我仍然知道几月是几号?如果这是一个愚蠢的问题,我深表歉意,但我只是不知道如何处理它。谢谢

一个简单的方法是建立一个索引数组,然后你可以对数据数组中对应项的值进行比较,然后对它进行排序,这样你就不会忘记这个月。

上述内容的简单 C# 实现如下:

        int[] CustomerByMonth = { 60, 50, 40, 30, 20, 10 };
        int[] index = { 0, 1, 2, 3, 4, 5 };

        int tmp = 0;
        for (int i = 0; i < index.Length; ++i)
        {
            for (int j = 0; j < index.Length - 1; ++j)
            {
                if (CustomerByMonth[index[j]] > CustomerByMonth[index[j + 1]])
                {
                    tmp = index[j + 1];
                    index[j + 1] = index[j];
                    index[j] = tmp;
                }
            }
        }

        // Display month number and customer amount for month with highest amount of customers
        Console.Write(index[CustomerByMonth.Length - 1] + " : " + CustomerByMonth[index[CustomerByMonth.Length - 1]]);