I have 2 float arrays. There's a K variable read from the keyboard. I have to insert into the 1st array the elements of the 2nd array after the value of K. Example:
array 1 (7 elements): 1, 2, 3, 4, 5, 6, 7 array 2 (3 elements): 9, 10, 11
Let's say K=4
array 1 becomes: 1, 2, 3, 4, 9, 10, 11, 5, 6, 7 (So K elements at a time from each array)
How would I move the elements to the right (in array 1) to insert the elements of array 2 (and repeat the process)? I'd prefer to avoid using any C++ 11 array functions (transform, sort etc.)
Since it sounds like homework, I only give you some hints about the solution, no full code.
Devide the task into two sub-tasks: Moving elements in the first array to the right by some offset (the number of elements to be inserted, i.e. the length of the second list), and moving elements from the second array to the first array where you just moved away the elements. Do not repeat this procedure for each element you insert, but rather move the elements by the (already known) size of the second array. This should be faster than what you described.
To avoid the need for a temporary copy (so it can be "in place", and in your comments you said you aren't allowed to allocate a third (temporary) array), you have to start moving elements from the end. This ensures that you don't overwrite values you later need, which would be the case if you started to move the elements from the left.
Let's say the part to be moved in the first array starts at some index start
(in your question this is K
I guess) and the whole array has length end
(i.e. end
is the index of the element "one past the end").
Write a loop which iterates through the source indices (i.e. where you read the old values) in your first array. Move them by the offset in your first array. Note that this loop, as explained above, iterates backwards, i.e. you need something like for (int index = end-1; index >= start; --index)
. This loop starts at the last element (end-1
; note that end
is the length and thus points after the array) and ends (inclusively) at start
.
After moving the elements to the right, you can start moving elements from the second array to the first. Here the order doesn't matter, so I would prefer iterating forward for simplicity.
As discussed below this answer, I assume that enough space is already allocated in array 1. Please make sure that this is the case in your code. Since you're not allowed to allocate a third array, there is no other option than this. (Unless you are allowed to use automatic allocation in the form of dynamic-sized data structures like std::vector
)