Home »
.Net »
C# Programs
C# program to insert an item into a sorted array
Here, we are going to learn how to insert an item into a sorted array in C#.Net?
Submitted by Nidhi, on May 22, 2021 [Last updated : March 19, 2023]
Inserting Item to Sorted Array
Given a sorted array and an item to be inserted, we have to insert the item in this sorted array.
C# code for inserting item to sorted array
The source code to insert an item into a sorted array is given below. The given program is compiled and executed successfully.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Declare to manage index of arrays
int index = 0;
//Location variable to store location in which we have to store the item.
int loc = 0;
//Item to be inserted
int item = 0;
//Declare array that contains 5 integer elements
int[] arr = new int[5];
//Now read values for 4 array elements.
Console.WriteLine("Enter value of array elements\n");
for (index = 0; index < arr.Length - 1; index++)
{
Console.Write("Element arr[" + (index + 1) + "]: ");
arr[index] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Enter item : ");
item = int.Parse(Console.ReadLine());
//Now we find location to store item
for (index = 0; index < arr.Length; index++)
{
if (item < arr[index])
{
loc = index;
break;
}
}
//Now we perform shift operations
for (index = 3; index >= loc; index--)
{
arr[index + 1] = arr[index];
}
//Copy item to location
arr[loc] = item;
Console.WriteLine("\nArray Elements\n");
for (index = 0; index < 5; index++)
{
Console.Write(arr[index] + " ");
}
Console.WriteLine();
}
}
}
Output
Enter value of array elements
Element arr[1]: 10
Element arr[2]: 20
Element arr[3]: 30
Element arr[4]: 40
Enter item :
25
Array Elements
10 20 25 30 40
Press any key to continue . . .
Explanation
In above program, search valid location to insert item into array then perform shift operation and copy item.
C# Basic Programs »