首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >有没有没有递归的快速排序的Python实现?

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

Stack Overflow用户
提问于 2021-07-26 10:59:53
回答 2查看 567关注 0票数 1

我试图在Python中不使用递归实现快速排序,但到目前为止,我发现的所有参考实现或伪代码都使用递归。

这样做的原因是,我将调整这个非递归实现,以运行在使用Numba的GPU上,并且我不能在那里进行递归调用。

是否有不使用递归的一维数组(例如,Numpy数组或Python列表)的快速排序实现?

谢谢,

爱德华多

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-07-26 11:13:35

为了提高效率,实现了标准的unix/linux qsort而不使用递归。你可以查一下,或者只是把这个答案中的代码翻译成python:

Can quicksort be implemented in C without stack and recursion?

票数 1
EN

Stack Overflow用户

发布于 2021-07-28 09:15:46

FWIW,这是一个Python版本:

代码语言:javascript
运行
复制
# 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])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68524038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档