【问题标题】:Counting Sort Method from Ascending to Descending order从升序到降序的计数排序方法
【发布时间】:2019-10-03 16:08:43
【问题描述】:

我对这个方法进行了编码,认为它是按降序排列的,但输出显示它是按升序排列的。 如何更改我的方法以按降序显示我的列表?

我尝试使用 FindMinValue 方法而不是最大值,但它给出了超出范围的错误。

  static int findMaxValue(int[] List)
    {
        int max = -1;
        for (int i = 0; i < List.Length; i++)
        {
            max = Math.Max(max, List[i]);
        }
        return max;
    }
    public static int findMinValue(int[] List)
    {
        //go through list to find min

        int min = int.MaxValue;
        for (int i = 0; i < List.Length; i++)
        {
            min = Math.Min(min, List[i]);
        }
        min = List[0];
        return min;
    }

    static void countingsort(int[] List, int max)

        // ADD CODE FOR METHOD countingsort BELOW
        Stopwatch timer = new Stopwatch();
            timer.Start();

        int[] countArray = new int[max + 1];
        for (int i = 0; i <= max; i++)
        {
            countArray[i] = 0;

        }
        for (int x = 0; x < List.Length; x++)
        {
            countArray[List[x]] = countArray[List[x]] + 1;
            // or countArray[List[x]]++;


        }
        int index = 0;
        for (int y = 0; y <= max; y++)
        {
            //List[y] = countArray[y];
            for (int j = 0; j < countArray[y]; j++)
            {
                List[index] = y;
                index = index + 1;
                // or index++
            }
        }
        timer.Stop();
        Display(List);
    }

【问题讨论】:

  • 当你遇到这种问题时,你所要做的就是反转比较逻辑,因为它是相反的

标签: c# arrays sorting counting


【解决方案1】:

通过倒计时给频繁项权重:换行

countArray[List[x]] = countArray[List[x]] + 1;

countArray[List[x]] = countArray[List[x]] - 1;

【讨论】:

  • 使用 findMin 或 findMax 方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-24
  • 2020-03-24
  • 1970-01-01
相关资源
最近更新 更多