select largest K number from unsorted array Python,largestunsorted

來源:互聯網
上載者:User

select largest K number from unsorted array Python,largestunsorted

heap:

take klog(n) time



code is as follow"

def siftdown(A, start, end):root = startchild = 2 * root + 1while child <= end:if child + 1 <= end and A[child] < A[child + 1]:child += 1if A[root] < A[child]:A[child], A[root] =  A[root], A[child]root = childelse:returndef heapify(A, count):start = (count - 2) / 2while start >= 0:siftdown(A, start, count - 1)start = start -1#def heapsort(A):#count = len(A)#heapify(A, len(A))#end = count - 1#while end > 0:#A[end], A[0] = A[0], A[end]#end -= 1#siftdown(A, 0, end)#return Adef topk(A, k):count = len(A)heapify(A, len(A))end = len(A) - 1while end > 0 and k > 0:A[end], A[0] = A[0], A[end]end -= 1k -= 1siftdown(A, 0, end)return A[end + s1:] #def drawmax(A):A = [3, 4, 5, 1, 2, 0]print topk(A, 3)


quick select take O(n) time find k values

import randomdef partition(num, pivotIndex, left, right):pivot = num[pivotIndex]num[pivotIndex], num[right] = num[right], num[pivotIndex]storeIndex = leftfor i in range(left, right):if num[i]< pivot:num[storeIndex], num[i] = num[i], num[storeIndex]storeIndex += 1num[storeIndex], num[right] = num[right], num[storeIndex]return storeIndexdef quickselect(num, k):left = 0right = len(num) - 1while True:pivotIndex = random.randint(left,right)pivotNewIndex = partition(num, pivotIndex,left, right)dist = pivotNewIndex - leftif dist == k:return num[pivotNewIndex]elif dist > k:right = pivotNewIndex - 1else:k -= (dist+1)left = pivotNewIndex + 1 num =[8, 9,0,1,2,3,6,7]print quickselect(num,3)







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.