非递归快排
Description
快速排序的核心思想是使用元素的值对数组进行划分。实现其非递归方案。
Input
输入的每一行表示一个元素为正整数的数组,所有值用空格隔开,第一个值为数值长度,其余为数组元素值。
Output
输出的每一行为排序结果,用空格隔开,末尾不要空格。
Sample Input 1
13 24 3 56 34 3 78 12 29 49 84 51 9 100
Sample Output 1
3 3 9 12 24 29 34 49 51 56 78 84 100
def partition(nums, low, high):
high_flag = True
low_flag = False
pivot = int(nums[low])
while low < high and low < len(nums) and high < len(nums):
if high_flag:
if int(nums[high]) < pivot:
nums[low] = str(nums[high])
high_flag = False
low_flag = True
else:
high -= 1
if low_flag:
if int(nums[low])> pivot:
nums[high] = str(nums[low])
high_flag = True
low_flag = False
else:
low += 1
nums[low] = str(pivot)
return low
def quickSort(nums):
arr = []
low = 0
high = len(nums) - 1
if low < high:
mid = partition(nums, 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(nums, l, r)
if l < mid - 1:
arr.append(l)
arr.append(mid - 1)
if mid + 1 < r:
arr.append(mid + 1)
arr.append(r)
#print(nums)
print(' '.join(nums))
if __name__ == '__main__':
a = []
s=input()
d=s.split()
a.extend(d)
del a[0]
quickSort(a)