The least intelligent sorting algorithm, it typically has the worst performance of sorting routines, and learns nothing to improve its actions as it traverse the array:
Class
using System;
namespace Algorithms
{
class SelectionSort
{
public SelectionSort()
{
int[] arrayToSort = { 11, 1, 22, 2, 33, 3, 44, 4, 55, 5, 66, 6, 7, 77 };
Sort(arrayToSort);
Console.WriteLine("End");
}
public int[] Sort(int[] arrayToSort)
{
int currentMin;
int max = arrayToSort.Length - 1;
for (int counter = 0; counter < max - 1; counter++)
{
currentMin = arrayToSort[counter];
int newMinCounter = counter;
for (int innerCounter = counter + 1; innerCounter < max; innerCounter++)
{
if (arrayToSort[innerCounter] < arrayToSort[newMinCounter])
{
//set new min
newMinCounter = innerCounter;
}
}
if (newMinCounter != counter)
{
//swap old value with new
arrayToSort[counter] = arrayToSort[newMinCounter];
arrayToSort[newMinCounter] = currentMin;
}
}
return arrayToSort;
}
}
}
Class
using System;
namespace Algorithms
{
class SelectionSort
{
public SelectionSort()
{
int[] arrayToSort = { 11, 1, 22, 2, 33, 3, 44, 4, 55, 5, 66, 6, 7, 77 };
Sort(arrayToSort);
Console.WriteLine("End");
}
public int[] Sort(int[] arrayToSort)
{
int currentMin;
int max = arrayToSort.Length - 1;
for (int counter = 0; counter < max - 1; counter++)
{
currentMin = arrayToSort[counter];
int newMinCounter = counter;
for (int innerCounter = counter + 1; innerCounter < max; innerCounter++)
{
if (arrayToSort[innerCounter] < arrayToSort[newMinCounter])
{
//set new min
newMinCounter = innerCounter;
}
}
if (newMinCounter != counter)
{
//swap old value with new
arrayToSort[counter] = arrayToSort[newMinCounter];
arrayToSort[newMinCounter] = currentMin;
}
}
return arrayToSort;
}
}
}
Comments
Post a Comment