0
How to shift elements of an array?
Say I have to insert an element into a certain index and there will be atleast 1 null at the end. In the array {3, 10, 7, 9, null} , I have to insert â2â at index 1 which is currently 10. I have to then shift 10, 7, and 9 to the right. How can I go about doing this?
4 Answers
+ 2
Since this is your homework, and we won't do it for you completely, you have to provide us with your attempt... Then we can guide you to solution
+ 2
I would use a for loop which starts at the end of your array and end at the given index.
for (int i = array.length - 1; i >= 1; i--){
}
inside the loop:
array [i] = array [i-1]
array [4] = array [3]
array [3] = array [2]
array [2] = array [1]
edit:
after the loop: array [1] = 2;
+ 1
Use list, not array
0
Take this as a hint....
Array has a constant size that is initialised whenever you declare an Array.
So if your Array is not full then you can shift the elements otherwise you have to Declare a new array of larger size.
There is no null node in array.
Use Loop for shifting the elements or you can use swap if you want to insert just one element.