面试遇到过让用非递归实现快速排列算法,递归好写,非递归的写法是通过列表的append和pop方法来实现的,类似于栈的性质。
主要思想是:每次把待排序数组分为两部分,左边小于轴右边大于轴,把分开的数组的收尾数组的索引存到辅助栈空间里,替换递归。
#这个函数是用来找出确定值的索引
def partition(li, low, high):
#首先设置俩个布尔变量,通过这个来控制左右移动
high_flag = True
low_flag = False
#将开始位置的值定为基数
pivot = li[low]
while low < high and low < len(li) and high < len(li):
#当这个值为真时,游标从右开始移动
if high_flag:
#找出右边比基数小的值,互换位置,否则一直向右移动
if li[high] < pivot:
li[low] = li[high]
#改变布尔值,控制方向
high_flag = False
low_flag = True
else:
high -= 1
if low_flag:
if li[low] > pivot:
li[high] = li[low]
high_flag = True
low_flag = False
else:
low += 1
li[low] = pivot
#返回的是索引位置
return low
def quickSort(li):
arr = []
low = 0
high = len(li) - 1
if low < high:
#mid是确定位置的索引
mid = partition(li, low, high)
#确定值左边
if low < mid - 1:
#将左边区的第一和最后数索引放进去
arr.append(low)
arr.append(mid - 1)
#确定值的右边
if mid + 1 < high:
arr.append(mid + 1)
arr.append(high)
#循环
while arr:
#依次取出一个区域的范围索引
r = arr.pop()
l = arr.pop()
#重复上面的找出该区域的可以确定下来的一个值的索引
mid = partition(li, l, r)
if l < mid - 1:
arr.append(l)
arr.append(mid - 1)
if mid + 1 < r:
arr.append(mid + 1)
arr.append(r)
return li
a = quickSort([3,1,6,4,9,5,7,8])
print(a)