首页 > 解决方案 > python的快速排序算法

问题描述

我尝试使用 numpy 算法为快速排序算法编写一些代码。但它似乎无法正常工作。你能帮我解决吗?

import numpy as np
def quick_sort_np(narr):
    """A numpy version of quick sort algorithm"""
    narr = np.array(narr)
    if len(narr)<= 1 :
        return narr
    p = narr[-1] # I take the last item as pivot by convension
    print (f"at this level the pivot is {p}")
    lnarr = narr[narr<p]
    print (f"----------------------> left arr is {lnarr}")
    rnarr = narr[narr>p]
    print (f"----------------------> right arr is {rnarr}")
    return quick_sort_np(lnarr) + p + quick_sort_np(rnarr) 

如果 [1,2,6,5,4,8,7,99,33] 作为输入,我的代码什么也不返回,这就是问题所在。

标签: pythonarraysnumpysortingquicksort

解决方案


+作用于 np.arrays 是元素加法,而不是串联。


推荐阅读