繁体   English   中英

计数排序:计数数组最小值,最大值和频率

[英]Counting Sort: count array minimum, maximum and frequency

我想修改计数排序,以有效地满足最小值不为0的一系列值。我的代码问题是如果它不是0则找到最小值,例如,最小值应该是,如果列表的范围是100 000 - 110 000,最小值是100 000.但是计数数组的频率(计数)不能是100 001我的代码当前不工作或者根据20 000个整数和数字的列表进行排序范围从1000 - 9999。

当min为0时它可以工作,但这并不是指如何有效地实现计数排序......

public static  int findMinValue(int[] List)
        {

            int min;
            min = List[0];
            return min;
        }

        static void countingsort(int[] List, int max)
        /* pre:  List has .Length integers in it. The maximum value in the list is max.
        * post: Using the countingsort algorithm, sort the list of integers into ascending order. */
        {

            // ADD CODE FOR METHOD countingsort BELOW
            Stopwatch timer = new Stopwatch();
                timer.Start();
            int[] countArray = new int[max + 1];
            int min = findMinValue(countArray);
            for (int i = 0; i <= max; i++)
            {
                countArray[i] = 0;

            }
            for (int x = 0; x < List.Length; x++)
            {
                countArray[List[x]] = countArray[List[x]] + min;
                // 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++
                }
            }
            Display(List);
            DisplayCount(countArray);
            timer.Stop();

            Console.WriteLine("Time Taken for Basic Selection Sort is {0} milliseconds", timer.ElapsedMilliseconds);



        }
        public static void DisplayCount(int[] Array)
        {
            int count = 0;
            for (int i = 0; i < Array.Length; i++)
            {
                count++;
            }
            Console.WriteLine("Elements in count array is {0} ", count);
        }

该列表未进行排序,它将count数组中的元素显示为10 000。

以下是我注意到的事情:

  1. 最小值查找功能从数组中获取第一个值,而不是实际最小值。 你可能想使用List.Min();

  2. countArray声明中,您应该使用最大值和最小值之间的差值+ 1作为大小。

  3. 在访问具有找到的最小值的countArray ,您需要偏移索引,因为0索引元素应该对应于最小值而不是0。

  4. 迭代countArray in for (int i = 0; i <= max; i++) ,不应在条件中使用max值。 除非最小值为0,否则它将与数组大小不同。

  5. 在计数显示功能中,您可以简单地使用Array.Length ,不需要遍历数组。

我不会为您提供算法本身的代码,因为它显然是一个Uni / College / HS分配。

暂无
暂无

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

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