Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shift elements in array

This is elementary, but my googling just doesn't cut it. I know I have to do something else to shift the values of an array one by one, but the below coding gives me the same values for items[k] to items[infinity] all equaling items[k]. What I don't understand is how to preserve the original k+1 value while I copy the k value into the k+1 slot.

if ( i < numItems) //if i is inside the used boundaries of the array
{
    for (int k = i; k < numItems; k++) //shift the array values from point i
    {
                double temp = 0.0;
        temp = items[k];
        items[k+1] = temp;
    }

    items[i] = value; //and insert value into i
}

Does it has to be a recursive method?

like image 583
Sukwoo Avatar asked Sep 28 '12 03:09

Sukwoo


People also ask

How do you shift an array element to the right?

An array is said to be right rotated if all elements of the array are moved to its right by one position. One approach is to loop through the array by shifting each element of the array to its next position. The last element of the array will become the first element of the rotated array.

How do you shift an array to the left?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.

Is shift () destructive?

Shift and Unshift are also both destructive methods, meaning they too will destructively change the array.

How do you shift elements in a 2D array?

To shift the bits of array elements of a 2D array to the left, use the numpy. left_shift() method in Python Numpy. Bits are shifted to the left by appending x2 0s at the right of x1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying x1 by 2**x2.


1 Answers

You can as well use memmove, that handles overlap of regions.

memmove(&items[k+1], &items[k], (numItems-k-1)*sizeof(double));
items[k] = value;
like image 116
Teudimundo Avatar answered Oct 21 '22 07:10

Teudimundo