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
outputof size $k$, this array is to store the top largest $k$ values from the arrayarrof 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 valueminExceptMinValueinoutputbut not counting theminValue(along with its indexminExceptMinIdx). We do this by:- In the first iteration: add
minValueto theoutputarray and setminValue = arr[0],minIdx = 0,minExceptMinValue= nullandminExceptMinIdx = null. - In the second iteration: Add
arr[1]tooutputand set values forminValue,minIdx,minExceptMinValue,minExceptMinIdxaccordingly (by comparingarr[1]andarr[0]). - In iteration
i:- If the length of
outputless than $k$: Append$arr[i]tooutputand updateminValue,minIdx,minExceptMinValue,minExceptMinIdx(by comparingarr[i],minValandminExceptMinValue). - If the length of
outputgreater than $k$: Compare the current valuearr[i]withminValue:- If
arr[i]>=minValue, then comparearr[i]withminExceptMinValue:- If
arr[i]>=minExceptMinValuesetminIdxtominExceptMinIdxandoutput[minIdx] = minExceptMinValuealsooutput[minExceptMinIdx]=arr[i]. - If
arr[i]<=minExceptMinValuesetoutput[minIdx] = arr[i].
- If
- If
- If the length of
- In the last iteration return the
outputarray.
- 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?