In this post, I will show you how to implement selection sort in c#. Before going to implement selection sort, let’s describe how selection sort works.
- Go through the list one item at a time.
- Keep track of the smallest item found.
- Find the smallest item out and add it to a list of sorted items.
- Repeat until all the items have been sorted
class Program
{
// Selection Sort Algorithm
public static void SelectionSort(int[] arr)
{
int i, j;
int min;
for (i = 0; i < arr.Length - 1; i++)
{
min = i;
for (j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
Swap(arr, i, min);
}
}
private static void Swap(int[] arr, int i, int min)
{
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 0, -3, 32 };
SelectionSort(arr);
}
}