C# Program to Sort an Array in Descending Order Using Insertion Sort

You are currently viewing C# Program to Sort an Array in Descending Order Using Insertion Sort

C# program to sort an array in descending order using insertion sort

//C# program to sort an array in descending order 
//using Insertion Sort.

using System;

class Sort
{
    static void InsertSort(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();

        InsertSort(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:
76 65 34 23 21
Press any key to continue . . .

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply