Selection Sorting with C-Sharp Example

Selection sort is a simple sorting algorithm that works by selecting the smallest element from the unsorted part of the array and placing it at the beginning of the sorted part of the array.

Here’s an example implementation of selection sort in C#:

public static void SelectionSort(int[] arr)
{
    if (arr == null || arr.Length == 0)
    {
        return;
    }

    int n = arr.Length;

    // Traverse the array from left to right
    for (int i = 0; i < n - 1; i++)
    {
        int minIndex = i;

        // Find the minimum element in the unsorted part of the array
        for (int j = i + 1; j < n; j++)
        {
            if (arr[j] < arr[minIndex])
            {
                minIndex = j;
            }
        }

        // Swap the minimum element with the first element of the unsorted part of the array
        int temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;
    }
}

In this implementation, we traverse the array from left to right and find the minimum element in the unsorted part of the array using the inner loop. We then swap the minimum element with the first element of the unsorted part of the array.

The time complexity of selection sort is O(n^2), where n is the number of elements in the array. This makes it inefficient for large arrays. However, it has the advantage of being easy to understand and implement, and it performs well on small arrays or arrays that are almost sorted.