Selection Sort Algorithm

The selection sort is using a combination of searching and sorting. Each unsorted element that has the smallest or largest value is moved to the proper position.

The inner loop (see the example) is used for the selection and this loop is searching for the smallest or largest value.
The outer loop is used for putting that value into its proper position.

The selection sort is not a very efficient sorting algorithm because the can’t end early (even if the sort begins with a sorted list.)

Take a look at the selection sort example:



#include<iostream>
using namespace std;

int main(void)
{
        int array[5];		// An array of integers.
        int length = 5;		// Lenght of the array.
        int i, j;
        int firstelement, temp;

	//Some input
	for (i = 0; i < length; i++)
	{
		cout << "Enter a number: ";
		cin >> array[i];
	}

	//Algorithm
        for (i= length - 1; i > 0; i--)
        {
           firstelement = 0;
           for (j=1; j<=i; j++)
           {
                 if (array[j] < array[firstelement])
                 firstelement = j;
           }
           temp = array[firstelement];
           array[firstelement] = array[i];
           array[i] = temp;
	}

	//Some output
	for (i = 0; i < 5; i++)
	{
		cout << array[i] << endl;
	}
}

That is all for this tutorial.

This entry was posted in Programming Algorithms. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There is currently one response to “Selection Sort Algorithm”

Why not let us know what you think by adding your own comment!

  1. vijay on August 29th, 2013:

    nice program

Leave a Reply: