C# Program to Implement Insertion Sort

C# Program to Implement Insertion Sort

Sorting is one of the most common tasks in programming, and Insertion Sort is a simple and intuitive algorithm that makes it easy to understand. Unlike Selection Sort, which finds the minimum element and swaps it into position, Insertion Sort builds the sorted array one element at a time, inserting each new element into its correct position. This method resembles how people often sort playing cards in their hands, which makes it easier for beginners to visualize.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Insertion Sort is particularly useful when dealing with small datasets or arrays that are already nearly sorted, because it performs efficiently in such cases. Learning this algorithm in C# is valuable because it teaches beginners how to work with arrays, loops, and conditional logic while providing a stepping stone to more advanced sorting techniques like Merge Sort or Quick Sort. Implementing it with predefined data helps beginners see exactly how elements move step by step.

Program 1: Insertion Sort Using Loops (Ascending Order)

This program demonstrates the classic Insertion Sort algorithm, sorting predefined numbers in ascending order.

using System;

class Program
{

    static void Main()
    {

        int[] arr = { 12, 11, 13, 5, 6 };
        int n = arr.Length;

        for (int i = 1; i < n; i++)
        {

            int key = arr[i];
            int j = i - 1;

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

            arr[j + 1] = key;

        }

        Console.WriteLine("Sorted array in ascending order:");

        foreach (int num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

In this program, the algorithm picks one element at a time (key) and shifts all larger elements one position to the right to make space for it. Beginners can easily follow how the sorted portion grows with each iteration.

Program 2: Insertion Sort in Descending Order

By adjusting the comparison condition, Insertion Sort can also sort arrays in descending order.

using System;

class Program
{

    static void Main()
    {

        int[] arr = { 12, 11, 13, 5, 6 };
        int n = arr.Length;

        for (int i = 1; i < n; i++)
        {

            int key = arr[i];
            int j = i - 1;

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

            arr[j + 1] = key;

        }

        Console.WriteLine("Sorted array in descending order:");

        foreach (int num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

This example shows how a small change in logic can reverse the sorting order. Beginners can see how Insertion Sort is flexible and easy to adapt for different scenarios.

Program 3: Insertion Sort With Strings

Insertion Sort can also be applied to string arrays, sorting them alphabetically. This example uses predefined strings.

using System;

class Program
{

    static void Main()
    {

        string[] arr = { "Orange", "Apple", "Banana", "Mango" };
        int n = arr.Length;

        for (int i = 1; i < n; i++)
        {

            string key = arr[i];
            int j = i - 1;

            while (j >= 0 && string.Compare(arr[j], key) > 0)
            {

                arr[j + 1] = arr[j];
                j--;

            }

            arr[j + 1] = key;

        }

        Console.WriteLine("Sorted string array:");

        foreach (string str in arr)
            Console.Write(str + " ");

        Console.WriteLine();

    }

}

This program demonstrates that Insertion Sort works not only with numbers but also with any type that can be compared, such as strings. Beginners can see how to use string.Compare to handle non-numeric data.

Program 4: Recursive Insertion Sort

Insertion Sort can also be implemented recursively, giving learners a different perspective on the same algorithm.

using System;

class Program
{

    static void InsertionSortRecursive(int[] arr, int n)
    {

        if (n <= 1)
            return;

        InsertionSortRecursive(arr, n - 1);

        int last = arr[n - 1];
        int j = n - 2;

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

        arr[j + 1] = last;

    }

    static void Main()
    {

        int[] arr = { 12, 11, 13, 5, 6 };

        InsertionSortRecursive(arr, arr.Length);

        Console.WriteLine("Recursive Insertion Sort (Ascending):");

        foreach (int num in arr)
            Console.Write(num + " ");

        Console.WriteLine();

    }

}

The recursive version demonstrates how repeated operations can be handled as function calls. Each call sorts one element, and beginners can understand recursion by observing how the array gradually becomes sorted.

Frequently Asked Questions (FAQ)

Q1: What is Insertion Sort?
Insertion Sort is a sorting algorithm that builds the sorted array one element at a time, inserting each new element into its correct position in the sorted portion.

Q2: When should I use Insertion Sort?
It is best for small datasets or nearly sorted arrays, where it performs efficiently and is easy to implement.

Q3: How does Insertion Sort differ from Selection Sort?
Insertion Sort shifts elements to make space for the new element, whereas Selection Sort repeatedly selects the minimum element and swaps it.

Q4: Can Insertion Sort sort strings or other data types?
Yes. As long as the data type can be compared, Insertion Sort can handle numbers, strings, or even custom objects with comparison logic.

Q5: Can Insertion Sort be implemented recursively?
Yes. Recursive Insertion Sort works by sorting the first n-1 elements and inserting the nth element, providing a clear way to learn recursion.

Conclusion

Insertion Sort is a simple and beginner-friendly sorting algorithm in C#. It helps learners understand how arrays are manipulated, how comparisons are made, and how elements are moved to their correct positions. By experimenting with ascending, descending, string-based, and recursive versions, beginners can strengthen their coding skills and gain confidence in solving sorting problems. Practicing with predefined data also helps beginners visualize the algorithm step by step, making it easier to learn more advanced sorting techniques in the future.

Scroll to Top