Java Programming insertBeginningint array int v insert an i
Java Programming:
insertBeginning(int[] array, int v ): insert an integer at the beginning of the array. Shift the elements. Size of the array should be the same.
insertEnd(int[] array, int v): insert an integer at the end of the array. Shift the elements. Size of the array should be the same
insertIndex(int[] array, int p, int v): insert v at index p of the array. Conserve all elements. Size of the array should increase by one.
Solution
Here are the codes for you:
class InsertElementsInArray
{
//insertBeginning(int[] array, int v ): insert an integer at the beginning of the array.
//Shift the elements. Size of the array should be the same.
public static int[] insertBeginning(int[] array, int v )
{
for(int i = array.length-2; i >= 0; i--)
array[i+1] = array[i];
array[0] = v;
return array;
}
//insertEnd(int[] array, int v): insert an integer at the end of the array.
//Shift the elements. Size of the array should be the same
public static int[] insertEnd(int[] array, int v)
{
for(int i = 1; i < array.length; i++)
array[i-1] = array[i];
array[array.length-1] = v;
return array;
}
//insertIndex(int[] array, int p, int v): insert v at index p of the array.
//Conserve all elements. Size of the array should increase by one.
public static int[] insertIndex(int[] array, int p, int v)
{
int[] newArray = new int[array.length + 1];
for(int i = 0; i < array.length; i++)
newArray[i] = array[i];
newArray[array.length] = v;
array = newArray;
return array;
}
}
![Java Programming: insertBeginning(int[] array, int v ): insert an integer at the beginning of the array. Shift the elements. Size of the array should be the sam Java Programming: insertBeginning(int[] array, int v ): insert an integer at the beginning of the array. Shift the elements. Size of the array should be the sam](/WebImages/43/java-programming-insertbeginningint-array-int-v-insert-an-i-1133684-1761606259-0.webp)