Selection Sort Algorithm in C#

1. Introduction

The Selection Sort algorithm sorts an array by repeatedly finding the minimum (or maximum, depending on sorting order) element from the unsorted part of the array and swapping it with the first unsorted element. It moves the boundary between sorted and unsorted segments one element to the right with each iteration.

2. Implementation Steps

1. Start from the first element of the array as the boundary between the sorted and unsorted segments.

2. Search for the smallest element in the unsorted segment.

3. Swap the smallest found element with the first unsorted element.

4. Move the boundary one element to the right and repeat the process until the entire array is sorted.

3. Implementation in C#

using System;
public class SelectionSort {
    public static void Sort(int[] arr) {
        int length = arr.Length;
        for (int i = 0; i < length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            if (minIndex != i) {
                // Swap arr[minIndex] and arr[i]
                int temp = arr[minIndex];
                arr[minIndex] = arr[i];
                arr[i] = temp;
            }
        }
    }
}
public class Program {
    public static void Main() {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        Console.WriteLine("Unsorted array:");
        foreach (var item in arr) {
            Console.Write(item + " ");
        }
        SelectionSort.Sort(arr);
        Console.WriteLine("\nSorted array:");
        foreach (var item in arr) {
            Console.Write(item + " ");
        }
    }
}

Output:

Unsorted array:
64 34 25 12 22 11 90
Sorted array:
11 12 22 25 34 64 90

Explanation:

1. The SelectionSort class houses a static method named Sort that sorts an integer array using the selection sort technique.

2. Within the Sort method, an outer loop (i) runs from the start to one less than the number of items in the array, marking the boundary between the sorted and unsorted segments.

3. An inner loop (j) searches for the smallest item in the unsorted segment.

4. Once the smallest item is identified, it is swapped with the first unsorted element unless it's already in its correct position.

5. The Main method showcases the sorting of an integer array employing the SelectionSort class, displaying both the unsorted and sorted arrays.


Comments