in Algorithms retagged by
480 views
5 votes
5 votes

Consider the following pseudocode for a function that operates on an $\textsf{N}$ element array $\textsf{A[1],A[2]},\dots,\textsf{A[N]}$ of integers.

function mystery (A[1...N])
{
    int i,j,position,tmp;
    for i=1 to N
    {
        position=i;
        for j=i+1 to N
        {
            if(A[j]<A[position])
            {
                position=j;
            }
        }
        tmp=A[i];
        A[i]=A[position];
        A[position]=tmp;
    }
}

If $\textsf{N = 100,}$ how many times is the comparison $\textsf{A[j] < A[position]}$ checked?

in Algorithms retagged by
480 views

1 Answer

7 votes
7 votes
In the first iteration, the comparison happens $99$ times. In the second iteration, it happens $98$ times. Overall, the comparison is checked $99+98+\cdots+1$ times, which adds up to $(99 \times 100) / 2=4950$ times.
edited by
Answer:

Related questions