Thursday, May 30, 2013

Implementing Selection Sort Algorithm in C++/C

SelectionSort method implements Selection Sort algorithm in the simplest way. This method you can use in C/C++ program. Method takes integer array and size the array to be sorted and sorts the array in place.
 

void SelectionSort(int * array, int nSize)
{
    if( NULL == array )
        return;
  
    if( nSize < 1 )
        return;

    for( int nIterator = 0; nIterator < nSize - 1; nIterator++)
    {
        int nCurrentLow = array[nIterator];
        int nPos = nIterator;
        for( int nTemp = nIterator +1; nTemp < nSize; nTemp++ )
        {
            if( nCurrentLow > array[ nTemp ] )
            {
                nCurrentLow = array[ nTemp ];
                nPos = nTemp;
            }
        }

        array[nPos] = array[ nIterator ];
        array[nIterator] = nCurrentLow;
    }
}

No comments:

Post a Comment