Question
Design and implement an algorithm that returns an array of the k largest elements of __A__ using a heap. the complexity must be Theta(klogn). I
Design and implement an algorithm that returns an array of the k largest elements of __A__ using a heap. the complexity must be Theta(klogn).
I created this algorithm below, it is perfectly successful at 10000 test cases but its time complexity is Theta(nlogn). Can you arrange this algorithm to create time complexity Theta(klogn). Please do not add any import heap or .sort methods, or any python built in methods( except pop, remove, del or append).!!!!!!!!!!!!!!!
Please read this carefully most of the time "Chegg experts" does not count what we want, it is not important to write an algorithm. The important thing is that we have to write it what they expect from us!!!! TY.!!!
def BiggestOutOfOrder(A, k): # YOUR CODE HERE build_max_heap(A) return A[-k:]
def max_heapify(A,n,i): l = left(i) r = right(i) if l < n and A[l] > A[i]: largest = l else: largest = i if r < n and A[r] > A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i] max_heapify(A,n,largest)
def left(i): return 2 * i + 1
def right(i): return 2 * i + 2
def build_max_heap(A): n = len(A) for i in range(n, -1,-1): max_heapify(A,n, i) for i in range(n-1,0,-1): A[0],A[i]=A[i],A[0] max_heapify(A,i, 0)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started