Categories

Tools

bitdefender

1&1 Web Hosting

Use the Selection Sort algorithm to sort an array of integers, with c plus plus


Selection Sort is a sorting algorithm, noted for its simplicity. It has performance advantages in certain situations, particularly where auxiliary memory is limited, but its asymptotic complexity is O(n2).

#include <iostream>
inline void selectionSort(int v[],int size)
{
	int i,j,temp;
	for (i=0; i<size; i++)
	{
		for (j=i+1; j<=size; j++)
		{
			if ( v[i] > v[j] )
			{
			temp = v[j];
			v[j] = v[i];
			v[i] = temp;
			}
		}
	}
}

int main()
{
// 
int SIZE = 10;
int vector[SIZE];

	for (int i=0; i<SIZE; i++)
	{
	std::cout<<"\nEnter element "<<i<<" of "<<(SIZE-1)<<" : ";
	std::cin>>vector[i];
	}

	// Print the array unordered
	std::cout<<"\nArray unordered: \n";
	for (int i=0; i<SIZE; i++)
	{
	std::cout<<vector[i]<<" ";
	}

	// Sort the array
	selectionSort(vector,SIZE);

	// Print the array ordered
	std::cout<<"\n\nArray ordered : \n";
	for (int i=0; i<SIZE; i++)
	{
	std::cout<<vector[i]<<" ";
	}

return 0;
}

This is an example of use:

Enter element 0 of 9 : 8
Enter element 1 of 9 : 5
Enter element 2 of 9 : 2
Enter element 3 of 9 : 6
Enter element 4 of 9 : 9
Enter element 5 of 9 : 3
Enter element 6 of 9 : 1
Enter element 7 of 9 : 4
Enter element 8 of 9 : 0
Enter element 9 of 9 : 7

Array unordered:
8 5 2 6 9 3 1 4 0 7

Array ordered :
0 1 2 3 4 5 6 7 8 9 

Animated example showing how the algorithm works

Selection Sort Animation

Joestape89 at the English language Wikipedia [GFDL or CC-BY-SA-3.0], via Wikimedia Commons

Posted in C++ by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.