The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+2 votes
129 views

Consider the following function that takes as input a sequence $A$ of integers with n elements, $A$$\left [ A1 \right ]$, $\left [ A2 \right ], \ldots, \left [ An \right ]$and an integer $k$ and returns an integer value. The function length$(S)$ returns the length of sequence $S$. Comments start with //.

function mystery(A, k){
n = length(A);
if (k > n) return A[n];
v = A[1];
AL = [ A[j] : 1 <= j <= n, A[j] < v ]; // AL has elements < v in A
Av = [ A[j] : 1 <= j <= n, A[j] == v ]; // Av has elements = v in A
AR = [ A[j] : 1 <= j <= n, A[j] > v ]; // AR has elements > v in A
if (length(AL) >= k) return mystery(AL,k);
if (length(AL) + length(Av) >= k) return v;
return mystery(AR, k - (length(AL) + length(Av)));
}
  1. Explain what the function computes.
  2. What is the worst-case complexity of this algorithm in terms of the length of the input sequence $A$?
  3. Give an example of a worst-case input for this algorithm.
asked in Algorithms by Boss (16.6k points)
edited by | 129 views

1 Answer

+2 votes
Best answer
a. Function computes kth smallest element (if k<number of elements in the array, else it returns max element).
b. Time complexity = $O(k$*$n)$, where n is the number of elements in the array.
c. Worst case input: Array consists of a distinct increasing sequence of numbers and from this sequence, if we need to find nth smallest (i.e. max element) then it will take O$(n$*$n)$ time.
answered by Veteran (55.4k points)
edited by
+1

basically worst case will be O(n2) when k=n

0
please explain how you got O(kn) time complexity

is this argument correct?

since in an increasing order of sequence the number of comparison decrease by 1

eg. in an increasing sequence of n elements the no. of comparisons to find k'th order would be

n + (n-1) + (n-2) + ... + (n-k)

from which you removed the constant negative terms and got O(kn)

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

39,782 questions
46,784 answers
140,766 comments
58,702 users