# Selection Sort Algorithm in C#

# Selection Sort Algorithm in C#

### A common sorting algorithm in computer science is the Selection Sort. We take a look at what it is using C# and how it performs.

Join the DZone community and get the full member experience.

Join For Free**The Architect’s Guide to Big Data Application Performance. Get the Guide.**

In this article, I am going to explain 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 the Selection Sort algorithm. Then, I will be providing C# code to execute it.

**The Selection Sort Algorithm**

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

- The subarray of sorted elements.
- 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's understand this with the help of an example.

Let's take an input array of **8 5 7 3 1**.

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

At the n^{th} 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 results in the complexity of Selection Sort as O(n²).

**Conclusion**

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

You can download the source code from here.

You can find my other articles on algorithms here.

**Learn how taking a DataOps approach will help you speed up processes and increase data quality by providing streamlined analytics pipelines via automation and testing. Learn More.**

Published at DZone with permission of Ankit Sharma , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

## {{ parent.title || parent.header.title}}

## {{ parent.tldr }}

## {{ parent.linkDescription }}

{{ parent.urlSource.name }}