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