Java program to insert an element into sorted array

Insert an element into sorted array

This program illustrate the concept to insert an element into sorted array.Inserting can be done in sorted or unsorted array.Here in this program we first sort the elements in ascending order.

import java.util.*;
class scan
{
 public static void main(String arg[])
  {
   int x[]=new int[100];
   int y,j,i,v,q,s;
   Scanner kb=new Scanner(System.in);
   System.out.println("Enter size of array");
   y=kb.nextInt();
   
   System.out.println("Enter Elements in Array:-");
   for(i=0;i<y;i++)
    {
	 x[i]=kb.nextInt();
	}
	
	for(i=0;i<y;i++)
	{
		for(j=i+1;j<y;j++)
		{
			if(x[i]>x[j])
			{
				v=x[i];
				x[i]=x[j];
				x[j]=v;
			}
		}
	}
	System.out.println("Sorted Array is:- ");
	 for(i=0;i<y;i++)
	 {
		 System.out.println(x[i]);
	 }
	 
	 System.out.println("Enter Location To Insert a Number");
	 q=kb.nextInt();
	 
	 System.out.println("Enter Number");
	 s=kb.nextInt();
	 
	 for(i=y;i>=q;i--)
	  {
	   x[i]=x[i-1];
	  }
	  y++;
	  x[q-1]=s;
	  System.out.println("New Array Is:-");
	  for(i=0;i<y;i++)
      {
	   System.out.println(x[i]);
	  }	  
	  
  }
}

OUTPUT:-

insert an element into sorted array


Comment below if you are facing any problem.


Also read

Java program to sort entered element in the Array
Java program to search an entered element in array
Java Program to find greatest Element in array


Summary
Java program to insert an element into sorted array
Article Name
Java program to insert an element into sorted array
Description
This program illustrate the concept to insert an element into sorted array.Inserting can be done in sorted or unsorted array.
Author
Publisher Name
Scanfcode
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *