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?
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):
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
.
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.