Insertion Sort
Insertion Sort is a sorting algorithm that takes an element at a time and inserts it in its correct position in the array. This process is continued until the array is sorted.
A program that demonstrates insertion sort in C# is given as follows.
using System;
public class Solution
{
static void InsertionSort(int[] arr)
{
for(int i = 0; i < arr.Length-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(arr[j-1] > arr[j])
{
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
foreach(var num in arr)
{
Console.Write(num + " ");
}
}
public static void Main(String[] args)
{
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp))
;
InsertionSort(arr);
}}
Output :
3 4 5 6 2 1
1 2 3 4 5 6
Insertion Sort is a sorting algorithm that takes an element at a time and inserts it in its correct position in the array. This process is continued until the array is sorted.
A program that demonstrates insertion sort in C# is given as follows.
public class Solution
{
static void InsertionSort(int[] arr)
{
for(int i = 0; i < arr.Length-1; i++)
{
for(int j = i+1; j > 0; j--)
{
if(arr[j-1] > arr[j])
{
int temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
foreach(var num in arr)
{
Console.Write(num + " ");
}
}
public static void Main(String[] args)
{
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), arrTemp => Convert.ToInt32(arrTemp))
;
InsertionSort(arr);
}
1 2 3 4 5 6