Python 使用队列的基数排序
我正在尝试创建一个基数排序,它使用队列进行排序。 我在队列类中使用的代码是basic,但它可以工作:Python 使用队列的基数排序,python,queue,radix-sort,Python,Queue,Radix Sort,我正在尝试创建一个基数排序,它使用队列进行排序。 我在队列类中使用的代码是basic,但它可以工作: class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, items): self.items.insert(0, items) #add item to t
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, items):
self.items.insert(0, items) #add item to the beginning
def dequeue(self):
return self.items.pop() # remove last item
def peek(self):
return self.items[len(self.items)-1] #First in line
def size(self):
return len(self.items)
据我所知,基数排序总共使用11个箱子。一个箱子装着所有的东西。其他10个箱子的标签从0到9。第一轮排序首先从主存储箱中删除1个数字,然后查看1处的数字,如果该数字是0,则将其放入0存储箱,如果是1,则将其放入1存储箱,依此类推。我们这样做,直到主容器中的所有数字都在“一”位值中排序,然后我们从零容器中取出这些数字,并将它们放回主容器中,然后在十位开始这个过程,然后在百位开始,依此类推。据我所知,基数排序仅在所有数据长度相同(或者我被告知是这样)的情况下才起作用。我假设在这一点上存在着距离
到目前为止,我的基数是:
def radix():
mainBin = Queue()
digList = [Queue()] * 10 #creates a list of 10 queues
numberList = random.sample(range(100000,999999), 10)
#This would normally be passed through, but this is easier for timing
#the sort
for num in numberList:
mainBin.enqueue(str(number))
while not mainBin.isEmpty():
temporary = []
number = mainBin.dequeue()
for digit in number:
temporary.append(digit)
if temporary[5] == '0':
digList[0].enqueue(temporary[5])
我在第一个
if
语句处停了下来,因为我意识到我必须对10个具有6个位值的数字执行此操作,这些位值具有10个数字的可能性。这就是if-elif
链的长度(19行代表一个位值…),但从逻辑上讲,这是我想到的第一件事。有谁能告诉我一个更好的解决方案吗?您可以运行for循环并使用索引,而不是硬编码目标队列
place = 6 # In this case you know it, but you could scan data to find it.
while place >= 0:
while not mainBin.isEmpty():
number = mainBin.dequeue()
digit = number[place]
digList[digit].enqueue(number)
place -= 1
# Reload mainBin logic goes here.
要扩展到不是每个数字字符串都具有相同长度的情况,可以根据需要使用零填充(取决于小数点的哪一侧)