Selection Sort in C# : Learn the Basics

Selection Sort in C# – Learn the Basics

Selection sort is another simple yet fundamental sorting algorithm. It works by repeatedly selecting the smallest element from the unsorted portion and placing it at the correct position in the sorted portion.

What is Selection Sort?

In each iteration, the algorithm scans the unsorted part of the array, finds the smallest element, and swaps it with the current position. This way, the smallest values are gradually moved to the front.

Selection Sort in C# – Learn the Basics

Steps

  • Start from index i = 0
  • Find the minimum element from index i to the end
  • Swap it with the element at index i
  • Repeat until the array is fully sorted

C# Code Example

int[] numbers = { 52, 86, 3, 79, 45, 12, 99, 23, 56, 78 };

for (int i = 0; i < numbers.Length; i++)
{
    int minIndex = i;

    for (int j = i + 1; j < numbers.Length; j++)
    {
        if (numbers[j] < numbers[minIndex])
        {
            minIndex = j;
        }
    }

    // Swap using tuple
    (numbers[i], numbers[minIndex]) = (numbers[minIndex], numbers[i]);
}

Console.WriteLine(string.Join(", ", numbers));

Why Is It Called "Selection Sort"?

The algorithm "selects" the smallest unsorted value at each step and moves it to its final position. This repeated selection process gives the algorithm its name.

Summary

Selection sort is intuitive and easy to implement, although not efficient for large data. It's excellent for understanding the basics of sorting. Next, we'll look at Insertion Sort, a method that works by inserting values into their correct position within the sorted section.

Popular posts from this blog

Understanding Arrays as Reference Types in C#

Setting Up a Basic Follow Camera with Cinemachine 3.x

Understanding and Using ? (nullable) in C#