The source code to implement insertion sort to arrange elements in the ascending order is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//C# program to sort an array in ascending order
//using Insertion Sort.
using System;
class Sort
{
static void InsertionSort(ref int []intArr)
{
int item = 0;
int pass = 0;
int loop = 0;
for (pass = 1; pass < intArr.Length; pass++)
{
item = intArr[pass];
for (loop = pass - 1; loop >= 0;)
{
if (item < intArr[loop])
{
intArr[loop + 1] = intArr[loop];
loop--;
intArr[loop + 1] = item;
}
else
break;
}
}
}
static void Main(string[] args)
{
int[] intArry = new int[5] { 65,34,23,76,21 };
Console.WriteLine("Array before sorting: ");
for (int i = 0; i < intArry.Length; i++)
{
Console.Write(intArry[i]+" ");
}
Console.WriteLine();
InsertionSort(ref intArry);
Console.WriteLine("Array before sorting: ");
for (int i = 0; i < intArry.Length; i++)
{
Console.Write(intArry[i] + " ");
}
Console.WriteLine();
}
}
Output:
Array before sorting:
65 34 23 76 21
Array before sorting:
21 23 34 65 76
Press any key to continue . . .
Explanation:
In the above program, we created a class Sort that contains two static methods InsertionSort() and Main(). The InsertionSort() method is used to sort the elements of integer array in the ascending order.
Now look to the Main() method, The Main() method is the entry point for the program. Here, we created the array of integers then sorted the array in ascending order using the InsertionSort() method and print the sorted array on the console screen.
Program:
The source code to implement insertion sort to arrange elements in the ascending order is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Sort that contains two static methods InsertionSort() and Main(). The InsertionSort() method is used to sort the elements of integer array in the ascending order.
Now look to the Main() method, The Main() method is the entry point for the program. Here, we created the array of integers then sorted the array in ascending order using the InsertionSort() method and print the sorted array on the console screen.