function retV = kthlargestvalue(inX,inRank)
%function [retV,retIdx] = kthlargestvalue(inX,inRank)
% Picking the k-th largest element in a vector.
% 
% Input:
%   inX: input vector;
%   inRank: k.
%
% Output:
%   retV: the k-th largest element in inX.
%
% Dabao Zhang     July 25, 2016
%
% Revised by:
%
% Copyright (c) 2016 by Dabao Zhang.

error(nargchk(1, 2, nargin));
if( nargin<2 ) inRank = 1; end

inRank = inRank-1;

while( 1 )
    % Start from a pivot (with the k-th element as the pivot value)
    retV = inX(inRank+1);
    
    % Consider elements smaller than the pivot value
    tmpLIdx = (inX>retV);
    tmpLNum = sum(tmpLIdx);
    
    if( inRank<tmpLNum )
        % retV is greater than the pivot value
        inX = inX(tmpLIdx);
    elseif( inRank<(tmpLNum+sum(inX==retV)) )
        % retV is the same as the pivot value 
        break ;
    else
        % retV is smaller than the pivot value
        inX = inX(inX<retV);
        inRank = inRank+length(inX)-length(tmpLIdx);
    end
end


