Write a program to demonstrate Insertion sort algorithm?
Solution:
For more information about Insertion sort read the article
using System;
using System.Collections.Generic;
namespace Sorting
{
class InsertionSort
{
static void Main()
{
int[] arr = { 16, 9, 5, 14, 11 };
Sort(arr);
Console.WriteLine($"Sorted:{string.Join(" ", arr)}");
Console.ReadLine();
}
static void Sort(IList<int> arr)
{
var n = arr.Count;
for (var i = 1; i < n; ++i)
{
var key = arr[i];
var j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
}
}