0
0
CsharpProgramBeginner · 2 min read

C# Program for Selection Sort Algorithm

A C# program for selection sort uses nested loops to repeatedly find the smallest element and swap it with the current position, like for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) minIndex = j; } int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; }.
📋

Examples

Inputarr = [5, 3, 8, 4, 2]
Output2 3 4 5 8
Inputarr = [1, 2, 3, 4, 5]
Output1 2 3 4 5
Inputarr = [9]
Output9
🧠

How to Think About It

To sort using selection sort, think of the array as divided into sorted and unsorted parts. Start from the first element, find the smallest value in the unsorted part, and swap it with the current element. Repeat this until the whole array is sorted.
📐

Algorithm

1
Start from the first element of the array.
2
Find the smallest element in the unsorted part of the array.
3
Swap the smallest element with the current element.
4
Move to the next element and repeat until the end of the array.
💻

Code

csharp
using System;
class Program {
    static void SelectionSort(int[] arr) {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
    static void Main() {
        int[] arr = {5, 3, 8, 4, 2};
        SelectionSort(arr);
        foreach (int num in arr) {
            Console.Write(num + " ");
        }
    }
}
Output
2 3 4 5 8
🔍

Dry Run

Let's trace the array [5, 3, 8, 4, 2] through the selection sort code.

1

First outer loop (i=0)

Find smallest from index 0 to end: smallest is 2 at index 4. Swap arr[0] and arr[4]. Array becomes [2, 3, 8, 4, 5].

2

Second outer loop (i=1)

Find smallest from index 1 to end: smallest is 3 at index 1. Swap arr[1] and arr[1] (no change). Array stays [2, 3, 8, 4, 5].

3

Third outer loop (i=2)

Find smallest from index 2 to end: smallest is 4 at index 3. Swap arr[2] and arr[3]. Array becomes [2, 3, 4, 8, 5].

4

Fourth outer loop (i=3)

Find smallest from index 3 to end: smallest is 5 at index 4. Swap arr[3] and arr[4]. Array becomes [2, 3, 4, 5, 8].

IterationArray State
i=0[2, 3, 8, 4, 5]
i=1[2, 3, 8, 4, 5]
i=2[2, 3, 4, 8, 5]
i=3[2, 3, 4, 5, 8]
💡

Why This Works

Step 1: Find the smallest element

The inner loop uses if (arr[j] < arr[minIndex]) to find the smallest element in the unsorted part.

Step 2: Swap elements

After finding the smallest element, the code swaps it with the element at the current position to place it correctly.

Step 3: Repeat for all elements

The outer loop moves the boundary of the sorted part forward until the entire array is sorted.

🔄

Alternative Approaches

Using LINQ to find minimum
csharp
using System;
using System.Linq;
class Program {
    static void SelectionSort(int[] arr) {
        int n = arr.Length;
        for (int i = 0; i < n - 1; i++) {
            int minValue = arr.Skip(i).Min();
            int minIndex = Array.IndexOf(arr, minValue, i);
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
    static void Main() {
        int[] arr = {5, 3, 8, 4, 2};
        SelectionSort(arr);
        foreach (int num in arr) Console.Write(num + " ");
    }
}
This uses LINQ to find the minimum but is less efficient due to extra overhead.
Recursive selection sort
csharp
using System;
class Program {
    static void SelectionSort(int[] arr, int start = 0) {
        if (start >= arr.Length - 1) return;
        int minIndex = start;
        for (int i = start + 1; i < arr.Length; i++) {
            if (arr[i] < arr[minIndex]) minIndex = i;
        }
        int temp = arr[minIndex];
        arr[minIndex] = arr[start];
        arr[start] = temp;
        SelectionSort(arr, start + 1);
    }
    static void Main() {
        int[] arr = {5, 3, 8, 4, 2};
        SelectionSort(arr);
        foreach (int num in arr) Console.Write(num + " ");
    }
}
This uses recursion instead of loops but can cause stack overhead for large arrays.

Complexity: O(n^2) time, O(1) space

Time Complexity

Selection sort uses two nested loops each running up to n times, resulting in O(n^2) time complexity.

Space Complexity

It sorts the array in place, so it uses only a constant amount of extra space, O(1).

Which Approach is Fastest?

The basic selection sort is simple but slow for large arrays; alternatives like quicksort or mergesort are faster but more complex.

ApproachTimeSpaceBest For
Selection SortO(n^2)O(1)Small or nearly sorted arrays
LINQ MinimumO(n^2)O(n)Readable code but less efficient
Recursive Selection SortO(n^2)O(n)Learning recursion, not for large data
💡
Always swap only after finding the smallest element to reduce unnecessary swaps.
⚠️
Beginners often swap elements inside the inner loop instead of after finding the minimum, causing incorrect sorting.