Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:
We have an array: array[] = 79 43 7 11 5
Find the minimum element in array[0…4]
and place it at beginning5 79 43 7 11
Find the minimum element in array[1…4]
and place it at beginning of array[1…4]5 7 79 43 11
Find the minimum element in array[2…4]
and place it at beginning of array[2…4]5 7 11 79 43
Find the minimum element in array[3…4]
and place it at beginning of array[3…4]5 7 11 43 79
Implementation in C# code
using System;
class Program
{
public static void Main()
{
int[] arr = { 79, 86, 97, 43, 64, 25, 12, 22, 11, 7, 23, 5 };
SelectionSort(arr);
Console.WriteLine("Sorted array");
PrintArray(arr);
}
private static void SelectionSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
private static void PrintArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
}
Output:
5 7 11 12 22 23 25 43 64 79 86 97