shift elements in array

96,534

Solution 1

An easy option would be to iterate through the array in reverse

for (int k = numItems; k > i; k--){        
    items[k]=items[k-1];
}

Option 2:

If you want to keep your method intact then you can also use the temp variable differently

before your for loop initialize temp to

double temp = items[i];

and then in the loop you can use temp to store the [k+1] value in temp rather than storing the [k] value.

items [k+1] = temp;
temp = items [k+1];
items[k+1] = items[k];

also you should watch your boundaries so that k+1 is not going past the last element in the array. You could use something like numItems - 1 with a check before, to ensure that the array is not empty.

Solution 2

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;
Share:
96,534
Sukwoo
Author by

Sukwoo

Updated on October 30, 2020

Comments

  • Sukwoo
    Sukwoo over 3 years

    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?

  • Frerich Raabe
    Frerich Raabe over 11 years
    Of course, after the memmove, you should set items[0] = value;
  • Teudimundo
    Teudimundo over 11 years
    You are right, and I've also corrected the answer to reflect the question (insert at the k-th position).
  • Teudimundo
    Teudimundo about 9 years
    You can find a nice discussion about this question here: stackoverflow.com/questions/7776085/…