Skip to main content

Selection Sort Algorithm In C#


In this article, I am going to explain about the Selection sort algorithm. It is an in-place comparison sorting algorithm. It is also a major question in job interviews.

So first, I am going to explain Selection Sort algorithm. Then, I will be providing a C# code to execute it.

The Selection sort Algorithm

This algorithm follows the concept of dividing the given array into two subarrays.

  1. The subarray of sorted elements
  2. The subarray of unsorted elements

The algorithm will find the minimum element in the unsorted subarray and put it into its correct position in the sorted subarray. Let us understand this with the help of an example.

Let us take an input array as – 8 5 7 3 1

The sorted output for this array is – 1 3 5 7 8

At nth iteration, elements from position 0 to n-1 will be sorted.

Iterations Input Array Sorted Array UnSorted Array
Iteration 1  8 5 7 3 1 1 5 7 3 8
Iteration 2 1 5 7 3 8 1 3 7 5 8
Iteration 3 1 3 7 5 8 1 3 5 7 8
Iteration 4 1 3 5 7 8 1 3 5 7 8
Iteration 5 1 3 5 7 8 1 3 5 7 8  

Hence, we got the sorted array in iteration 5.

Time Complexity

Every element needs to be compared to every other element and then get swapped to its correct position. After every iteration, the size of unsorted array reduces by 1.

Hence n swaps and (n*(n-1))/2 comparisons result in the complexity of Selection Sort as O(n²).

See Also


In this tutorial, we learned about the Selection Sort algorithm and its implementation using C#.

You can download the source code from here

Ankit Sharma

Software engineer having more than 4 years of extensive experience in MS technologies including but not limited to C#, ASP.NET MVC and MSSQL. I am also an author at C# corner and currently working on ASP.NET Core and Angular 5.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.