Algorithm

Selection Sort Algorithm In C#

Introduction

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.

IterationsInput ArraySorted ArrayUnSorted Array
Iteration 1 8 5 7 3 115 7 3 8
Iteration 21 5 7 3 81 37 5 8
Iteration 31 3 7 5 81 3 57 8
Iteration 41 3 5 7 81 3 5 78
Iteration 51 3 5 7 81 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

Conclusion

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

Full Stack Consultant | GDE for Angular | Microsoft MVP | Author | Speaker | Passionate Programmer

Recent Posts

Announcing A New Blazor Course

Introduction Blazor is a .NET web framework that allows us to create client-side applications using…

3 years ago

How To Solve Sudoku Using Azure Form Recognizer

Introduction In this article, we are going to create a sudoku solver with the help…

4 years ago

Going Serverless With Blazor

Introduction In this article, we will learn how to implement Azure serverless with Blazor web…

4 years ago

Announcing A Free eBook On Angular and Firebase

Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…

5 years ago

Optical Character Reader Using Angular And Azure Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Angular…

5 years ago

Optical Character Reader Using Blazor And Computer Vision

Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…

5 years ago