Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selection Sort program in C#
Selection Sort is a sorting algorithm that finds the minimum value in the array for each iteration of the loop. Then this minimum value is swapped with the current array element. This procedure is followed until the array is sorted in ascending order.
The algorithm divides the array into two parts: a sorted portion (initially empty) and an unsorted portion (initially the entire array). In each iteration, it selects the smallest element from the unsorted portion and moves it to the end of the sorted portion.
How Selection Sort Works
Time Complexity
Selection Sort has a time complexity of O(n²) in all cases (best, average, and worst). This is because the algorithm always performs the same number of comparisons regardless of the input data arrangement.
Example
A program that demonstrates selection sort in C# is given as follows −
using System;
public class Example {
static void Main(string[] args) {
int[] arr = new int[10] { 56, 1, 99, 67, 89, 23, 44, 12, 78, 34 };
int n = 10;
Console.WriteLine("Selection sort");
Console.Write("Initial array is: ");
for (int i = 0; i
The output of the above code is −
Selection sort
Initial array is: 56 1 99 67 89 23 44 12 78 34
Sorted array is: 1 12 23 34 44 56 67 78 89 99
Using a Generic Method
Here's a more reusable implementation using a generic method −
using System;
public class SelectionSortGeneric {
public static void SelectionSort(T[] array) where T : IComparable {
int n = array.Length;
for (int i = 0; i
The output of the above code is −
Original: John Alice Bob Charlie Diana
Sorted: Alice Bob Charlie Diana John
Comparison with Other Sorting Algorithms
Algorithm
Time Complexity
Space Complexity
Stable
Selection Sort
O(n²)
O(1)
No
Bubble Sort
O(n²)
O(1)
Yes
Insertion Sort
O(n²)
O(1)
Yes
Quick Sort
O(n log n)
O(log n)
No
Conclusion
Selection Sort is a simple comparison-based sorting algorithm with O(n²) time complexity. While not efficient for large datasets, it performs well on small arrays and has the advantage of making the minimum possible number of swaps (n-1 swaps for n elements). It's an in-place sorting algorithm that requires only O(1) additional memory space.
