【问题标题】:Improved Selection Sort Out of Bounds Error改进的选择排序越界错误
【发布时间】:2019-05-16 13:22:44
【问题描述】:

我有一种方法是“选择排序的改进版本”。但是,代码没有运行为“ temp[x] = 0;”此行给出了超出数组范围的错误。我不想使用 ArrayList。我如何将这条线更改为在数组的范围内?

    public static void ImprovedSelectionSort(int[] Array)
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        int[] temp = new int[Array.Length];
        for (int x = 1; x <= Array.Length; x++)
        {
            //OtherList.Add(0); -- what I want to do
            temp[x] = 0;
        }

        int n = Array.Length;
        int i = 0;
        while (i < n)
        {
            int rear = 0; 
            int curMax = Array[i]; 
           temp[rear] = i; 
            int j = i + 1;

            while (j < n)
            {
                if (curMax < Array[j])
                {
                    curMax = Array[j];
                    rear = -1;
                }
                if (curMax == Array[j])
                {
                    rear = rear + 1;
                    temp[rear] = j;
                }
                j++;
            }
            int front = 0;
            int p = Array[temp[front]];
            while (front <= rear)
            {
                int temporary = p;
                Array[temp[front]] = Array[i];
                Array[i] = temporary;
                i++;
                front += 1;
            }
        }

【问题讨论】:

  • for (int x = 1; x &lt;= Array.Length; x++) {temp[x] = 0;} - C# 中的数组从零开始,你可能想要for (int x = 0; x &lt; Array.Length; x++) {temp[x] = 0;}

标签: c# arrays sorting


【解决方案1】:

for (int x = 1; x

这很可能是问题所在。数组中的最后一个索引是长度减 1(因此,一副 52 张牌从 0..51 开始)。将“x

【讨论】:

    【解决方案2】:

    在 for 循环中将

    【讨论】:

      猜你喜欢
      • 2014-06-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2016-04-12
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      相关资源
      最近更新 更多