快速排序的基本思想是:找一个基准值(如可以选最左边的值或者随机选择一个值或者选择最右边的值作为基准值),然后通过一趟遍历,将数组分为两部分,其中一部分的数据都比基准值小,另一部分的数据都比基准值大,然后再递归的解决子问题,即对分割好的两部分再进行排序,直到子问题中只剩下一个元素时,一个元素肯定是有序的。
所以该算法可以通过上述思路进行递归排序,今天面试的时候被问到非递归怎么实现,ummmmm问懵了,于是就有了今天的非递归实现,主要是通过数据结构——栈实现,具体实现代码如下
'''
快排的非递归实现,需要用到栈的数据结构,利用栈存储需要排序的边界索引,当栈为空时则全部排序好
需要一个函数,这个函数可以实现输入一个列表和左右边界,返回一个基准值在该列表中的索引位置,及该索引左边的元素均
小于该索引对应的元素,该索引右边的元素对应的值均大于该基准值
'''
import collections
def partSort(arr, left, right):
pivot = arr[left]
while left < right:
while left < right and arr[right] > pivot:
right -= 1
if right > left:
arr[left],arr[right] = arr[right],arr[left]
left += 1
while left < right and arr[left] <= pivot:
left += 1
if left < right:
arr[left],arr[right] = arr[right],arr[left]
right -= 1
return left
def QuickSort(arr):
n = len(arr)
if n == 0: return arr
left,right = 0,n - 1
stack = collections.deque()
stack.append(left)
stack.append(right)
while stack:
left = stack.popleft()
right = stack.popleft()
Index = partSort(arr, left, right)
if Index - 1 > left:
stack.append(left)
stack.append(Index - 1)
if Index + 1 < right:
stack.append(Index + 1)
stack.append(right)
return arr
array = [1, 5, 3, 10, 15, 9, 12, -6, 0, 6, 5]
print(QuickSort(array)) #[-6, 0, 1, 3, 5, 5, 6, 9, 10, 12, 15]