Selection Sort Algorithm

Although it may not be the best array sorting algorithm, it’s good enough to sort small arrays. Here’s my implementation of the algorithm in C++ :

void selectionSort(int a[], int length)
{
    //Three variables that will be used later
    int min, minAt, temp;

    for (int i = 0; i < length-1; i++) //Outer loop to go through the passes
    {
        //Suppose that the first element is the minimum
        min = a[i];
        minAt = i;

        for (int j = i+1; j < length; j++) //Inner loop to go through the elements in each pass. Notice that we don’t touch previously processed elements
        {
            //If an element smaller than the minimum is encountered, then set the minimum to be equal to that element
            if (min > a[j])
            {
                min = a[j];
                minAt = j;
            }
        }

        //Finally swap the current element with the minimum that was found
        temp = a[i];
        a[i] = a[minAt];
        a[minAt] = temp;
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s