I have an array that holds a history of values, and when adding a new value, I need to shift all previous values one position to the left, to loose the oldest value and make room for the next.
I can think of two ways of doing this, by using memmove:
memmove(&arr[0], &arr[1], sizeof(arr) - sizeof(*arr));
Or by swapping the pointers:
for (i = 0; i != sizeof(arr) - 1; i++) {
*(arr + i) = *(arr + i + 1);
}
Is there a performance difference between the two methods, and if not, which one would be advised?
Logic To Shift Elements of An Array by n Position. First we ask the user to input N integer numbers and store it inside array variable a[N]. We then ask the user to input the number of positions to shift the elements of the array, and then the direction of shifting.
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.
Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.
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.
There is a faster option:
A circular buffer where insert, remove and read are all O(1).
They both have the same time complexity. Any other difference in performance would be due to specific circumstances, such as the CPU, the compiler, how memmove is implemented, and the size of the array, so you have to actually measure the performance each way and see what is best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With