Selection Sort in C# – Programming Empire

Related Articles

This article explains C # selection sorting. Like bubble sorting and income sorting, selection sorting is also a simple sorting technique. Furthermore, selection sorting also works by dividing the list into a sorted and non-sorted part. Unlike income sorting, selection sorting finds the minimum element from the unsorted list and places it at the beginning. Moreover, the element initially moves to the position of the minimum element. Therefore, now the first element also becomes part of a sorted list. Initially, the entire list is not sorted. So, this algorithm finds the minimum from the whole list and replaces it with the element in the first position. Then, the sorted list contains one element and an unsorted list contains n-1 elements, where n is the total number of elements. The same process is repeated for the other elements. The following example illustrates the selection sort operation.

Work of selection selection

Let, our list is [9, 1, 22, 5, 18, 12]. At first, unsorted part = [9, 1, 22, 5, 18, 12] , And a sorted part =[]. So, we find a minimum from the whole list = 1. This causes the elements 1 and 9 to be replaced. Now the list becomes [1, 9, 22, 5, 18, 12]. Furthermore, find the minimum from the unsorted portion. So, minimum = 5. Then replace it with the element 9. So, now we get the following list = [1, 5, 22, 9, 18, 12] . In the next step we will get the following list [1, 5, 9, 22, 18, 12]. Similarly, the following iteration leads to this list: [1, 5, 9, 12, 18, 22]. Although our list is organized now. But the last iteration also occurs.

C # selection selection application

The following code shows the C # selection sorting application. While, the inner loop finds minimum element. Also, the replacement function replaces the current element with the minimum element.

using System;
namespace SelectionSort
    class Program
        static void Main(string[] args)
            int[] myarray =  4, 1, 9, -13, 90, 56, 81, 34, -2, -15, 60, 88 ;
            Console.WriteLine("Array before sorting...");
            foreach (int x in myarray)
                Console.Write(x + "  ");
            Console.WriteLine("nArray after sorting...");
            foreach (int x in myarray)
                Console.Write(x + "  ");
    class Sort
        public static void SelectionSort(int[] myarray)
            int min_index;
            for (int i = 0; i < myarray.Length - 1; i++)
                min_index = i;
                for (int j = i + 1; j < myarray.Length; j++)
                    if (myarray[j] < myarray[min_index])
                        min_index = j;
                swap(ref myarray[i], ref myarray[min_index]);
        static void swap(ref int m, ref int n)
            int t = m;
            m = n;
            n = t;


C # selection selection application



Please enter your comment!
Please enter your name here

Popular Articles