Insertion Sort in C# : Learn the Basics

Insertion Sort in C# – Learn the Basics

Insertion sort is a simple and intuitive sorting algorithm. It works by taking one element at a time and inserting it into its proper place in the already sorted part of the array. This makes it especially efficient for small or nearly sorted datasets.

What is Insertion Sort?

The idea is similar to how you sort playing cards in your hands. You pick up one card at a time and place it into the right position relative to the already sorted cards.

Insertion Sort in C# – Learn the Basics

Steps

  • Start from the second element (index 1)
  • Compare the current element (key) with the left part of the array
  • Shift larger values to the right
  • Insert the key into the correct position
  • Repeat until the entire array is sorted

C# Code Example

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

for (int i = 1; i < numbers.Length; i++)
{
    int key = numbers[i];
    int j = i - 1;

    while (j >= 0 && numbers[j] > key)
    {
        numbers[j + 1] = numbers[j];
        j--;
    }

    numbers[j + 1] = key;
}

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

Why Is It Called "Insertion Sort"?

Because at each step, the algorithm inserts the current value into its correct position within the sorted portion. This repeated insertion action gives the algorithm its name.

Summary

Insertion sort is straightforward and effective for small or nearly sorted arrays. It performs well when the data is already almost in order, with best-case time complexity of O(n). Although it is not the most efficient for large datasets, it's a valuable algorithm for understanding the basics of sorting.

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#