Q:

C# program to insert an item into a sorted array

belongs to collection: C# Basic Programs | array programs

0

C# program to insert an item into a sorted array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

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 . . .

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to delete an item from a sorted array... >>
<< C# program for swapping of two arrays...