Search code examples
c++algorithmarray-algorithms

Am I interpreting this pseudocode wrong?


I've got this pseudocode:

COMPARE-EXCHANGE(A,i,j)
    if A[i] > A[j]
        exchange A[i] with A[j]

INSERTION-SORT(A)
    for j = 2 to A.length
        for i = j-1 downto 1
            COMPARE-EXCHANGE(A,i,i+1)

I would interpret it as:

void insertSort( )
{
    int tmp;

    for( int j = 2 ; j < MAX ; ++j )
    {
        for( int i = j - 1 ; i > 0 ; --i )
        {
            if( unsortedArr[i] > unsortedArr[i + 1] )
            {
                tmp                 = unsortedArr[i];
                unsortedArr[i]      = unsortedArr[i + 1];
                unsortedArr[i + 1]  = tmp;
            }
        }
    }
}

However that would skip unsortedArr[0]. Which means it won't work.

Changing the 2nd for to:

for( int i = j - 1 ; i >= 0 ; --i )

Will make it run as intended. Is there a mistake in the pseudocode or was my first try of interpreting it wrong?


Solution

  • However that would skip unsortedArr[0]. Which means it won't work.

    It is nearly universal for pseudocode to number array elements from 1, not from zero, as in C/C++

    Changing the 2nd for to:

    for( int i = j - 1 ; i >= 0 ; --i )

    Will make it run as intended.

    That is not enough: you also need to start j at 1 rather than 2 in the outer loop.

    Also note that the C++ standard library offers a std::swap function which takes care of exchanging the elements of the array for you:

    if( unsortedArr[i] > unsortedArr[i + 1] )
    {
        std::swap(unsortedArr[i], unsortedArr[i+1]);
    }