Suppose that we have a sorted int array x with n elements in it and some room to add more elements.

QUESTION

Suppose that we have a sorted int array x with n elements in it and some room to add more elements. Write the code segment in Java that would add a new item, called target, to the array so that the array will still be sorted once you are done.

 

SUMMARY

An array is initialized with certain/given values in sorted order. Another array which is the target array is also initialized and each element in this target array should be inserted in the original array in a sorted manner.

 

EXPLANATION

An array named ‘x’ is first declared with 6 elements which are given and are displayed as the initial array. The array ‘target’ is then declared with elements(also given). Each element in the target array is taken and it is made sure that it is placed in the correct position of array ‘x’ such that even after extending the array with the target array, the elements are in the sorted order.

For example in the given code, element ‘2’ is supposed to be placed in index -1. For this to happen all the elements after 1 are moved by one step towards the right and then ‘2’ could be placed in index-1 of the original array.

After all, this has been done, the array x is printed as the output.

 

CODE

class Main 

{

    public static void main(String args[])

    {

        /* initial array */

        int x[]=new int[10];

        x[0]=1;x[1]=3;x[2]=5;x[3]=7;x[4]=8;x[5]=9;

        int no=6;

        System.out.println("Array initially:");

        for(int j=0;j<n;j++)

        System.out.print(x[j]+" ");

        System.out.println("\n");

        /* Target array */

        int target[]={2,4,6};

        /* inserting elements of target array in its position in the intial array */

        for(int i=0;i<3;i++)

        {

            int index=-1;

            for(int j=0;j<n;j++)

            {

                if(target[i]<x[j])

                {

                    index=j;

                    break;

                }

            }

            no++;

            if(index==-1)

                x[no-1]=target[i];

            else 

            {

                for(int k=no-1;k>index;k--)

                    x[k]=x[k-1];

                x[index]=target[i];

            }

        }

        System.out.println("Final Array:");

        for(int i=0;i<no;i++)

        System.out.print(x[i]+" ");

    }

}

 

Output:

 

Share this post

Leave a Reply

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