Site Loader

Is a linear sort algorithm which focus on moving through an array and put in each position the smaller corresponding element in the same array.

The Selection Sort Algorithm run the array’s elements from its first to the last and for each position look in their next elements a smaller value than the current and if is found then make a switch of values in the two the position.

It has O n2 time complexity which make it inefficient on large lists. Generally performs better than bubble and worse than the insertion sort.

For Example: Having the following list: 3,5,1,2 where bold element means the current position.

1st Iteration:

[3, 5, 1, 2]

The algorithm look for the smallest element in the array after the current index which in this iteration is 3, the result will be 1.

So the array will end like this: [1, 5, 3, 2]

2nd Iteration:

[1, 5, 3, 2]

The algorithm look for the smallest element in the array after the current index which in this iteration is 5, the result will be 2.

The result will be: [1, 2, 3, 5] already sorted but the iteration isn’t over yet….

3rd and 4th Iteration:

The Algorithm will look for the smallest element in the array after the current index but won’t find any because is already sorted.

The result will remain the same: [1,2,3,5]

And after iteration finish we’ll end up with a sorted array [1,2,3,5].

Here I am going to give you a .NET example:

public class SortAlgorithms<T> where T : IComparable<T>
{

public void SortSelection(T[] items)
 {
 int indexInfo = 0;
 while (indexInfo < items.Length)
 {
 int smallestInt = FindSmallestInt(items, indexInfo);
 var temp = items[indexInfo];
 items[indexInfo] = items[smallestInt];
 items[smallestInt] = temp;
 indexInfo++;
 }
 }

public int FindSmallestInt(T[] items, int indextorganized)
 {
 int smallestInt = indextorganized;
 T ChoosenValue = items[indextorganized];
 for (int count = indextorganized; count < items.Length; count++)
 {
 if (items[count].CompareTo(ChoosenValue) < 0)
 {
 smallestInt = count;
 ChoosenValue = items[count];
 }
 }
 return smallestInt;
 }
}

See the full example here: https://github.com/edgarleonardo/SelectionSort
I hope this help you.
Good Luck!

Post Author: Edgar Leonardo

I am Full Stack Developer and DevOps passionate, result-driven with deep experience on IT concerns. I am always seeking the best knowledge and practices in the world of technologies that make me and my work improve every day.

With more than 10 years of experience working as an IT professional, I have been involved and in some case leading large-scale IT projects since Backend, Frontend, Mobile Applications, Cloud Solutions and API integrations and even DevOps for Latam and the Caribbean in areas like Finance, Banking, Digital Advertising, Search engines, Social Network, Software Development, Outsourcing and Freelancer, integrations and more.