function [TH_MAP, y_predict_bin] = THfunc(y_predict_prob, y_ground_truth)
%THfunc determines the threshold via MAP criterion 

    y_predict_prob_vec = y_predict_prob(:);%probability-style prediction of training examples
    y_ground_truth_vec = y_ground_truth(:);%ground-truth label of training examples

    [yp_val_ascend, yp_idx_ascend] = sort(y_predict_prob_vec);%ascending order
    yg_val_ascend = y_ground_truth_vec(yp_idx_ascend);

    Len = length(yp_idx_ascend);
    Acc = zeros(Len+1,1);
    Acc(1) = sum(yg_val_ascend);
    for iLen=1:Len
        if yg_val_ascend(iLen)%true
            Acc(iLen+1) = Acc(iLen)-1;
        else
            Acc(iLen+1) = Acc(iLen)+1;
        end
    end

    [~, Acc_idx] = max(Acc);%ascending order
    if Acc_idx==1
        TH_MAP = yp_val_ascend(Acc_idx)-1;%smaller than yp_val_ascend(1)
    elseif Acc_idx==Len+1
        TH_MAP = yp_val_ascend(end)+1;%larger than yp_val_ascend(end)
    else
        TH_MAP = (yp_val_ascend(Acc_idx-1)+yp_val_ascend(Acc_idx))/2;
    end
    y_predict_bin = (y_predict_prob>TH_MAP)+0;
end