Python 迭代快速排序程式
在本文中,我們將瞭解如何解決下面給出的問題陳述。
問題陳述 − 給定一個數組,我們需要使用迭代方式對該陣列進行快速排序
這裡我們首先對陣列進行分割槽,然後對各個分割槽排序,以得到已排序的陣列。
現在讓我們在下面的實現中檢視解決方案−
示例
# iterative way
def partition(arr,l,h):
i = ( l - 1 )
x = arr[h]
for j in range(l , h):
if arr[j] <= x:
# increment
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[h] = arr[h],arr[i+1]
return (i+1)
# sort
def quickSortIterative(arr,l,h):
# Creation of a stack
size = h - l + 1
stack = [0] * (size)
# initialization
top = -1
# push initial values
top = top + 1
stack[top] = l
top = top + 1
stack[top] = h
# pop from stack
while top >= 0:
# Pop
h = stack[top]
top = top - 1
l = stack[top]
top = top - 1
# Set pivot element at its correct position
p = partition( arr, l, h )
# elements on the left
if p-1 > l:
top = top + 1
stack[top] = l
top = top + 1
stack[top] = p - 1
# elements on the right
if p+1 < h:
top = top + 1
stack[top] = p + 1
top = top + 1
stack[top] = h
# main
arr = [2,5,3,8,6,5,4,7]
n = len(arr)
quickSortIterative(arr, 0, n-1)
print ("Sorted array is:")
for i in range(n):
print (arr[i],end=" ")輸出
Sorted array is 2 3 4 5 5 6 7 8

所有變數都在區域性作用域中宣告,並且在上圖中可以看到它們的引用。
結論
在本文中,我們瞭解瞭如何製作 Python 迭代快速排序程式。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP