Python 2.7中的建议的无限循环问题

时间:2016-12-17 06:28:52

标签: python algorithm python-2.7

这是我的代码,在未排序的数组中找到第k个最小元素,代码将进入无限循环。我理解为什么会有无限循环(请参阅我的评论),但我修复它们的想法有点乱,想知道是否有任何优雅的解决方案?

顺便说一句,我不想​​排序。我希望在没有排序的情况下找到优雅的解决方案,并且能够在所有元素相等时处理这种情况。

使用Python 2.7。

def find_kth(numbers, start, end, k):
    if end == start:
        if k == 1:
            return numbers[start]
        else:
            raise Exception('invalid input!')

    mid_index = start + (end - start) / 2
    mid_value = numbers[mid_index]
    origin_start = start
    origin_end = end

    while start <= end:
        while start <= end and numbers[start]<=mid_value:
            start += 1
        while start <= end and numbers[end] > mid_value:
            end -= 1
        if start < end:
            numbers[start], numbers[end] = numbers[end], numbers[start]
        else:
            if start-origin_start == k:
                return mid_value
            elif start-origin_start > k:
                return find_kth(numbers, origin_start, start-1, k) # infinite loop here
            else:
                return find_kth(numbers, start, origin_end, k-(start-origin_start))

if __name__ == "__main__":
    numbers = [5,5,5,5]
    find_kth(numbers, 0, len(numbers)-1, 2) # find the 2nd smallest element, I count element from one, other than from zero

1 个答案:

答案 0 :(得分:2)

一个班轮怎么样?!

>>> def find_kth(numbers, start, end, k):
...     return sorted(numbers[start:end])[k]
... 
>>> 
>>> find_kth([5,5,5,5], 0, 4, 2)
5
>>> find_kth([1,5,2,3], 0, 4, 2)
3