Techiehook Techiehook
Updated date Jun 23, 2024
This article provides how to implement an insertion sort algorithm using C#.

Insertion Sort in C#

Insertion Sort is a simple sorting algorithm that is used to sort the arrays at a time. It is much like sorting and playing cards in your hands.

C# Program:

using System;

class InsertionSortSampleProgram
{
    // Method to perform insertion sort
    public static void InsertionSort(int[] array)
    {
        int n = array.Length;
        for (int i = 1; i < n; ++i)
        {
            int key = array[i];
            int j = i - 1;

            // Move elements of array[0..i-1], that are greater than key,
            // to one position ahead of their current position
            while (j >= 0 && array[j] > key)
            {
                array[j + 1] = array[j];
                j = j - 1;
            }
            array[j + 1] = key;
        }
    }

    // Method to print the array
    public static void PrintArray(int[] array)
    {
        int n = array.Length;
        for (int i = 0; i < n; ++i)
            Console.Write(array[i] + " ");
        Console.WriteLine();
    }

    // Main method to test the Insertion Sort algorithm
    static void Main()
    {
        int[] array = { 22, 11, 15, 8, 4, 10, 18, 2 };
        Console.WriteLine("Original array:");
        PrintArray(array);

        InsertionSort(array);

        Console.WriteLine("Sorted array:");
        PrintArray(array);
        Console.ReadKey();
    }
}

Output:

Original array:
22 11 15 8 4 10 18 2
Sorted array:
2 4 8 10 11 15 18 22

 

ABOUT THE AUTHOR

Techiehook
Techiehook
Admin, Australia

Welcome to TechieHook.com! We are all about tech, lifestyle, and more. As the site admin, I share articles on programming, tech trends, daily life, and reviews... For more detailed information, please check out the user profile

https://www.techiehook.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!