简体   繁体   中英

Counting Sort Method from Ascending to Descending order

I coded this method thinking it is in descending order but the output displays it as ascending order. How would I change my method to display my list in descending order?

I tried to use a FindMinValue method instead of the max value but it gives an out of bounds error.

  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);
    }

Give frequent items less weight by counting down : Change the line

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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