Problem 2. C-11.37 Suppose we wish to support a new met

Added on - 16 Sep 2019

  • Dissertation


  • 2


  • 483


  • 78


  • 0


Showing pages 1 to 1 of 2 pages
Problem 2C-11.37Suppose we wish to support a new methodcountRange(k1,k2)thatdetermineshow many keys of a sorted map fall in the specified range. We could clearlyimplement this inO(s+h)time by adapting our approach tosubMap. Describehow to modify the search-tree structure to supportO(h)worst-case timeforcountRange.Problem 3Suppose we are given an n-element sequence S such that each element in Srepresents a different vote in an election, where each vote is given as an integerrepresenting the ID of the chosen candidate. Suppose the number of candidates runningis k < n. Describe an O(n log k)-time algorithm for determining who wins the election.Below is the sample of solutionProblem 1:Explanation: This algorithm will find the kth smallest element in these array, we start with twoarray with same size but after we trim the array the array size will be different. So we have tomake sure the smaller one always on top. This Algorithm trim the array by compare the value atS[K/2 - 1] and T[K/2 -1] ,if S[i] > T[j], trim the arrays to left side of S[i], and right side of T[j], k= k-j.if S[i]<T[j], the other way around,k = k-i. We can find the Kth smallest until k = 1.Complexity: O(log(M+N)) -> O(logn)Algorithm FindKthSmallest (k, ArrayS , ArrayT , SizeS, SizeT )// O(logn)//Pre-Cond: ArrayS,ArrayT two sorted Array//Post-Cond: output Kth smallest element in ArrayS U ArrayT// If Size T smaller than SizeS make a swapIf (SizeS > SizeT)then return FindKthSmallest(k, ArrayT , ArrayS , SizeT, SizeS)//Case when no element in a arrayIf(SizeS == 0 && SizeT > 0)Then return T[k - 1]//base caseIf(k==1)
You’re reading a preview

To View Complete Document

Become a Desklib Library Member.
Subscribe to our plans

Unlock This Document