Selection Sort
Written by
Selection Sort
It is a sorting algorithm mainly performs an in-place comparison sort. Selection sort cannot be said to be very efficient on large lists.
Selection sort is a very simple algorithm and also has performance advantages over other sorting algorithms. Selection sort has a complexity of O(n²), where n is the number of items being sorted.
# Steps followed in the algorithm
- Find the minimum value in the list
- Swap it with the value at the first pos
- Repeat the process till the last value is read and swapped.
# Algorithm
// selection sort
for (i = 0; i < array; i++;)
{
pos = min_pos_search(list, i);
temp = list[pos];
list[pos] = list[i];
list[i] = temp;
}
Code:
//Program to show selection sort
#include<iostream>
using namespace std;
int smallestNum(int[], int);
int main()
{
int array[5] = {
20,
5,
12,
35,
48
};
int position, temp, iter = 0;
cout << "\n Input list of elements to be Sorted\n";
for (int i = 0; i < 5; i++)
{
cout << array[i] << "\t";
}
for (int i = 0; i < 5; i++)
{
position = smallestNum(array, i);
temp = array[i];
array[i] = array[position];
array[position] = temp;
iter++;
}
cout << "\n Sorted list of elements is\n";
for (int i = 0; i < 5; i++)
{
cout << array[i] << "\t";
}
cout << "\nNumber of iterations required to sort the array: " << iter;
return 0;
}
int smallestNum(int array[], int i)
{
int small, pos, j;
small = array[i];
pos = i;
for (j = i + 1; j < 5; j++)
{
if (array[j] < small)
{
small = array[j];
pos = j;
}
}
return pos;
}