简体   繁体   English

是否有没有递归的快速排序的 Python 实现?

[英]Is there a Python implementation of quicksort without recursion?

I am attempting to implement quick sort in Python without using recursion, but all reference implementations or pseudo codes I have found so far use recursion.我试图在不使用递归的情况下在 Python 中实现快速排序,但到目前为止我发现的所有参考实现或伪代码都使用递归。

The reason for this is that I will adapt this non-recursive implementation to run on GPUs using Numba, and I cannot make recursive calls there.这样做的原因是我将调整此非递归实现以在使用 Numba 的 GPU 上运行,并且我无法在那里进行递归调用。

Is there a quick sort implementation for a 1d array (say, a Numpy array or Python list) that does not use recursion?是否有不使用递归的一维数组(例如,Numpy 数组或 Python 列表)的快速排序实现?

Thanks,谢谢,

Eduardo爱德华多

The standard unix/linux qsort is implemented without recursion for efficiency.标准的 unix/linux qsort 是在没有递归的情况下实现的,以提高效率。 You could look that up, or just translate the code in this answer to python:你可以查一下,或者只是把这个答案中的代码翻译成python:

Can quicksort be implemented in C without stack and recursion? 可以在没有堆栈和递归的情况下在 C 中实现快速排序吗?

FWIW, this is a Python version: FWIW,这是一个 Python 版本:

# This function is same in both iterative and recursive
def partition(arr,l,h):
    i = ( l - 1 )
    x = arr[h]
  
    for j in range(l , h):
        if   arr[j] <= x:
  
            # increment index of smaller element
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]
  
    arr[i+1],arr[h] = arr[h],arr[i+1]
    return (i+1)
  
# Function to do Quick sort
# arr[] --> Array to be sorted,
# l  --> Starting index,
# h  --> Ending index
def quickSortIterative(arr,l,h):
  
    # Create an auxiliary stack
    size = h - l + 1
    stack = [0] * (size)
  
    # initialize top of stack
    top = -1
  
    # push initial values of l and h to stack
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = h
  
    # Keep popping from stack while is not empty
    while top >= 0:
  
        # Pop h and l
        h = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1
  
        # Set pivot element at its correct position in
        # sorted array
        p = partition( arr, l, h )
  
        # If there are elements on left side of pivot,
        # then push left side to stack
        if p-1 > l:
            top = top + 1
            stack[top] = l
            top = top + 1
            stack[top] = p - 1
  
        # If there are elements on right side of pivot,
        # then push right side to stack
        if p+1 < h:
            top = top + 1
            stack[top] = p + 1
            top = top + 1
            stack[top] = h
  
# Driver code to test above
arr = [4, 3, 5, 2, 1, 3, 2, 3]
n = len(arr)
quickSortIterative(arr, 0, n-1)
print ("Sorted array is:")
for i in range(n):
    print ("%d" %arr[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM