I came up with the following algorithm to select top (largest) $k$ values in an array arr
containing $n$ comparable values ($k \le n$):
- Initialize an empty array
output
of size $k$, this array is to store the top largest $k$ values from the arrayarr
of size $n$. - Iterate through the array
arr
, and in each iteration we will keep track of the minimum item valueminValue
(and its indexminIdx
) inoutput
, also the minimum valueminExceptMinValue
inoutput
but not counting theminValue
(along with its indexminExceptMinIdx
). We do this by:- In the first iteration: add
minValue
to theoutput
array and setminValue = arr[0]
,minIdx = 0
,minExceptMinValue= null
andminExceptMinIdx = null
. - In the second iteration: Add
arr[1]
tooutput
and set values forminValue
,minIdx
,minExceptMinValue
,minExceptMinIdx
accordingly (by comparingarr[1]
andarr[0]
). - In iteration
i
:- If the length of
output
less than $k$: Append$arr[i]
tooutput
and updateminValue
,minIdx
,minExceptMinValue
,minExceptMinIdx
(by comparingarr[i]
,minVal
andminExceptMinValue
). - If the length of
output
greater than $k$: Compare the current valuearr[i]
withminValue
:- If
arr[i]
>=minValue
, then comparearr[i]
withminExceptMinValue
:- If
arr[i]
>=minExceptMinValue
setminIdx
tominExceptMinIdx
andoutput[minIdx] = minExceptMinValue
alsooutput[minExceptMinIdx]=arr[i]
. - If
arr[i]
<=minExceptMinValue
setoutput[minIdx] = arr[i]
.
- If
- If
- If the length of
- In the last iteration return the
output
array.
- In the first iteration: add
My first estimation for the time complexity of this algorithm is n
but it's all wrong because otherwise, I would have won the Nobel prize for it since the fastest algorithm for the selection problem is $\sim n\ln(n)$.
But still, I don't see what's wrong with my estimation that the above algorithm's (time) complexity is $\sim n$, it goes through the array just once, isn't it?