0

So basically I want to figure out how to reverse a counting sort. This is the code I found:

def countingSort(myList):
    maxValue = 0
    for i in range(len(myList)):
        if myList[i] > maxValue:
            maxValue = myList[i]

    buckets = [0] * (maxValue + 1)

    for i in myList:
        buckets[i] += 1

    i = 0
    for j in range(maxValue + 1):
         for a in range(buckets[j]):
             myList[i] = j
             i += 1

    return myList

if __name__ == '__main__':
    sortedList = countingSort([1,23,4,5,6,7,8])
    print(sortedList)

So I decided to change line 16 to this:

i -= 1

The results are very close, but I get this:

[1, 23, 8, 7, 6, 5, 4]

My issue is that 1 is before 23 for some reason. I tried reverting some of the other signs, but it usually results in an out of bounds error. Any ways to work around it?

3
  • 2
    Can't you just use sorted function or .sort method? Commented Dec 5, 2020 at 23:54
  • what is your desired output? Commented Dec 5, 2020 at 23:59
  • @MarkMeyer eh, basically, most of the introductory CS material, the intro-to-programming stuff, was all created with languages like C or Java, where you are working with primitive arrays and C-style for-loops. Most of the education AFAIKT is just Java in Python. Unfortunate. Commented Dec 6, 2020 at 0:07

3 Answers 3

2

Reverse the range that j iterates through so you start from high numbers then end with low numbers:

for j in range(maxValue, -1, -1):
Sign up to request clarification or add additional context in comments.

2 Comments

or the more readable (IMO) reversed(range(maxValue + 1))
These are correct, but you'll need i += 1 so it doesn't loop around backwards again, or you'll get [23, 1, 4, 5, 6, 7, 8]
0

With i -= 1 you're writing at indices 0, -1, -2, -3 etc. That is, you write the smallest number (the 1) at the front, and then the remaining numbers from the back backwards. You can make it work by starting with i = -1.

Comments

0
int j=largest;
    for(int i=0;i<count.length;i++){
        while(count[i]>n){
            arr[j] = i;
            j--;
            count[i]++;

use this in case of reversing an array for counting sort

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.