概述
一般来说我们实现快速排序是使用递归的方式来调用,但是这种 方式往往在调用过程中会造成栈溢出的问题,所以最好的取代方式 是通过队列来模拟实现递归
下面就是快速排序通过队列的方式来实现
# encoding: utf-8
import queue
def quick_queue_sort(array):
work_queue = queue.Queue()
quick_data = QuickData(0, len(arr) - 1, arr)
work_queue.put(quick_data)
while work_queue.qsize() > 0:
data = work_queue.get_nowait()
i = data.head
j = data.tail
compare = array[data.head]
if j > i:
while j > i:
while j > i and array[j] >= compare:
j -= j
array[i] = array[j]
while j > i and array[i] <= compare:
i += i
array[j] = array[i]
array[i] = compare
work_queue.put(QuickData(data.head, i - 1, array))
work_queue.put(QuickData(i + 1, data.tail, array))
class QuickData:
def __init__(self, head, tail, array):
self.head = head
self.tail = tail
self.array = array
if __name__ == '__main__':
arr = [1, 8, 9, 121, 122, 5, 8, 4, 9, 1, 6, 45, 9, 125, 6546, 16546]
quick_queue_sort(arr)
print(arr)
最后
以上就是贤惠鞋子为你收集整理的使用python使用队列来实现快速排序的全部内容,希望文章能够帮你解决使用python使用队列来实现快速排序所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复