Reputation: 31
Is there an easy method to swap sections (chunks) of arrays with each other? That is, I have an array:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
array[6] = 7;
array[7] = 8;
and a function called swapSections(startX, endX, startY, endY)
which pretty much given these values swaps out the range of values determined by endX - startX
with the range of values from StartY
to endY
, so from my example...
if x range = 2
and startX = 0
and y range = 3
and startY = 5
, it would place array[0] and array[1] to where array[5] and array[6] are, and then place array[7] after array[6], pushing everything else down one. I am not sure how to go about this, and I was physically copying the memory across to a temp array, but I think there is a better way to do this. (btw, the end result from my example would be):
array[0] = 6;
array[1] = 7;
array[2] = 8;
array[3] = 3;
array[4] = 4;
array[5] = 5;
array[6] = 1;
array[7] = 2;
Upvotes: 2
Views: 2437
Reputation: 18651
Assume you have (or can create) a function to reverse a range of elements in place, something like reverse(array, start, end)
. You can then perform this task in four steps:
// (1) reverse the first range
array[0] = 2;
array[1] = 1;
// (2) reverse the elements between the ranges
array[2] = 5;
array[3] = 4;
array[4] = 3;
// (3) reverse the second range
array[5] = 8;
array[6] = 7;
array[7] = 6;
// (4) finally, reverse the entire array
array[0] = 6;
array[1] = 7;
array[2] = 8;
array[3] = 3;
array[4] = 4;
array[5] = 5;
array[6] = 1;
array[7] = 2;
Spoiler: (do your homework first then read this)
If you are allowed to use the Standard Library there is a
std::reverse
function in<algorithm>
that makes this trivial.
Upvotes: 1
Reputation: 47418
The easiest way to swap sections of an array in terms of readability and effort is to use the standard C++ function swap_ranges()
#include <iostream>
#include <algorithm>
int main()
{
int a[8] = {1,2,3,4,5,6,7,8};
std::cout << "Beforeswap: ";
for(int i=0; i<8; ++i)
std::cout << a[i] << ' ';
std::cout << '\n';
std::swap_ranges(a+0, a+2, a+5);
std::cout << "After swap: ";
for(int i=0; i<8; ++i)
std::cout << a[i] << ' ';
std::cout << '\n';
}
test: https://ideone.com/ZVv2M
...but it will only swap subranges of equal length, not the unequal length as in your test case. Your case is actually a combination of swap_ranges()
and rotate()
.
Upvotes: 3
Reputation: 22904
One approach you can take in your example is swapping the minimum range and then "bubbling up" the last part. So:
array[0] = 1; --> 6
array[1] = 2; --> 7
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6; --> 1
array[6] = 7; --> 2
array[7] = 8;
Then you bubble up the 8 by swapping array[7], with array[6], then array[6] with array[5], etc. until you put the 8 in the right place. Hopefully that gets you started.
Upvotes: 1