Selection Sort Algorithm
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 earch 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.
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!
Edgar Perez
Comments
Post a Comment