python第K小快速排序

我必须获得未排序数组中的第 K 个最小元素。我不想对整个数组进行排序,而是只尝试对包含第 K 个元素的子数组进行排序。然后我打印从 0 到 len(array) 的所有 K 个值


array = [6,5,4,3,2,1]

def quick_sort(lst, k):

    if len(lst) <= 1:

        return lst

    else:

        p = (lst[0] + lst[len(lst)-1])/2

        left = [x for x in lst if x <= p]

        right = [x for x in lst if x > p]

        

        if  k > len(left) -1 :

            k = k - len(left)+1

            return quick_sort(right,k)

        else:

            return quick_sort(left, k)

  

for i in range(len(array)):    

    print(*quick_sort(array,i+1))

我想要得到 1,2,3,4,5,6,但我的代码得到 2,3,5,6,6,6。我需要改变什么?


PS 主要思想不是对所有数组进行排序,也不使用 python 排序函数


陪伴而非守候
浏览 1570回答 1
1回答

千巷猫影

array = [6, 5, 4, 3, 2, 1]def quick_sort(lst, k):&nbsp; &nbsp; if len(lst) <= 1:&nbsp; &nbsp; &nbsp; &nbsp; return lst&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; p = (lst[0] + lst[-1]) / 2&nbsp; &nbsp; &nbsp; &nbsp; left = [x for x in lst if x <= p]&nbsp; &nbsp; &nbsp; &nbsp; right = [x for x in lst if x > p]&nbsp; &nbsp; &nbsp; &nbsp; if k > len(left):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; k = k - len(left)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return quick_sort(right, k)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return quick_sort(left, k)for i in range(len(array)):&nbsp; &nbsp; print(*quick_sort(array, i + 1))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python