Selection sort

Updated: 15.09.2019

Selection sort – an array sorting algorithm that is comparable in speed with bubble sorting.

Description of the selection sorting algorithm

The selection sorting algorithm consists of the following steps:

  • First, determine the position of the minimum element of the array;
  • We make an exchange of the minimum element with the element at the beginning of the array. It turns out that the first element of the array is already sorted;
  • Reduce the working area of ​​the array, discarding the first element, and for the subarray that happened, repeat the sorting.

Implementing sort by selection

using System;
class program
{
    // method for finding the position of the minimum element of a subarray, starting at position n
    static int IndexOfMin(int[] array, int n)
    {
        int result = n;
        for (var i = n; i < array.Length; ++i)
        {
            if (array[i] < array[result])
            {
                result = i;
            }
        }

        return result;
    }

    // method for exchanging elements
    static void Swap(ref int x, ref int y)
    {
        var t = x;
        x = y;
        y = t;
    }

    // selection sort
    static int[] SelectionSort(int[] array, int currentIndex = 0)
    {
        if (currentIndex == array.Length)
            return array;

        var index = IndexOfMin(array, currentIndex);
        if (index != currentIndex)
        {
            Swap(ref array[index], ref array[currentIndex]);
        }

        return SelectionSort(array, currentIndex + 1);
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Sort by selection");
        Console.Write("Enter elements of the array:");
        var s = Console.ReadLine().Split(new[] { "", ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
        var a = new int[s.Length];
        for (int i = 0; i < s.Length; i++)
        {
            a[i] = Convert.ToInt32(s[i]);
        }

        Console.WriteLine("Ordered array: {0}", string.Join(",", SelectionSort(a)));
        Console.ReadLine();
    }
}

The result of the program: Selection sorting algorithm

comments powered by Disqus