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
Joestape89 at the English language Wikipedia [GFDL or CC-BY-SA-3.0], via Wikimedia Commons