top k
def top_k(arr, left, right, k): if left >= right: return pivot = arr[right] index = left for i in range(left, right): if arr[i] < pivot: arr[i], arr[index] = arr[index], arr[i] index += 1 arr[index], arr[right] = arr[right], arr[index] num = index-left+1 if num == k: return elif num < k: top_k(arr, index+1, right, k-num) else: top_k(arr, left, index-1, k) from random import randint a=[] for i in range(30): a.append(randint(0, 20)) print a top_k(a, 0, len(a)-1, 5) print a print a[:5]
采用快排思路来做,上面的输出:
[9, 2, 10, 10, 12, 20, 18, 7, 15, 12, 17, 1, 16, 6, 17, 0, 16, 10, 18, 4, 1, 10, 14, 15, 4, 9, 11, 7, 3, 20] [2, 1, 0, 1, 3, 18, 7, 15, 12, 17, 9, 16, 6, 17, 10, 16, 10, 18, 4, 10, 10, 14, 15, 4, 9, 11, 7, 12, 20, 20] [2, 1, 0, 1, 3]
注意:k个元素未必是有序的!