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
Comments (0)