You are on page 1of 3

a) Since the question asks for two largest number and not to sort them

we can do it like this:(Lets call our array A)


max1=max2=Integer.smallest //Depending on programming language, this will equal
to smallest integer that programing language permits.
for j=1 to A.length
if max1<A[j]
max2=max1
max1=A[j]

return max1,max2
b)
//max is an array of k element which elements are initially equals to Integer.sm
allest
max=[Integer.smallest,Integer.smallest,.........Integer.smallest]
i=2
for j=1 to A.length
if max[1]<A[j]
max[i]=max[1]
max[1]=A[j]
i=i%k
// I am not sure about we can use mod operation as primitive operations
// but if we cannot we can use if statements when we reach i=k and then put it i
=1 and then increase it
//if i==k
//i=1
i=i+1

return max // it will return an array consisting of k largest elements

c)Considering an algorithm that I have used to solved a and b, when searching k


largest elements
where k is comparible with array size:
for j=2 to A.length ===>N times
if max[1]<A[j]=====>N-1 times
//In worst case scenario
max[i]=max[1]===> N-1
max[1]=A[j]=====>N-1
i=i%k =========>N-1

i=i+1=========>N-1
return max ====>1 times
-->O(n)=N+5*(N-1)+1=6N-4. But we can just say that efficiency is related to N.
(Also as I stated in question b, if we cannot do mode operation, our calculated
efficiency will be little different but it can also be simplified as N, or we ca
n say
efficiency is related to Array size and they show linear relation).

-->I think we cannot find more efficient algorithm than that is dependant of arr
ay size N.But we can decrease the constant factors that effects our efficiency.
If we scan our array and compare if that element is bigger than our max[1], ther
e is no way we can do comparison less than our max array's size k. But if we do
not only
think about worst case scenario and try to find N-k smallest elements in array(b
ecause of k is near N, N-k would be small), and if these N-k smallest elements a
ppears not
at the end of the array, we would skip most of the if statesment's body and it w
ill reduce our constant terms in efficiency analysis. After finding N-k smallest
elements
we can delete these and form new array that contains k largest elements of previ
ous array or we can store where those minimum values are and then create new arr
ay considering that.

//min is an array of size N-k that has elements initially equals to Integer.larg
est and max is an array of size k that has elements initially equals to zero.
//minIndex is an array of size N-k that has elements initially equals to zero.
i=2
t=1
c=1
for j=2 to A.length
if min[1]>A[j]
min[i]=[1]
max[1]=A[j]
i=i%k
minIndex[i]=j
t=t+1
i=i+1
minIndex[1]=A[t]

for k=1 to A.length


for m=1 to minIndex.length
if k==minIndex[m]
break
max[c]=A[k]
c=c+1

return max
-->In worst case scenario this will take longer than the previous algorithm.

You might also like