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
所有变量都在局部作用域中声明,并且在上图中可以看到它们的引用。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
结论
在本文中,我们了解了如何制作 Python 迭代快速排序程序。
广告