void MyArray::shift_elements(int index,int pl)
{
for(int k=0;k<pl;k++)
{
int temp;
for (int i=0; i<(index -1); i++)
{
temp = storage[index-1];
storage[index-1] = storage[i];
storage[i] = temp;
}
}
}
Any shifting algorithm that requires swapping or a nested loop is inefficient. Do it all in one shot. If you are shifting right four spaces, then you should set up a temporary array for the four right-most bytes, copy them into that temporary array, then have ONE loop that moves each remaining byte right 4 places. No swaps are necessary. When the shift is complete, copy the temporary array to the beginning of the permanent array.
As an alternate to the loop, you can also use the memmove function from the cstring library.
http://www.cplusplus.com/reference/clibrary/cstring/memmove/
VernonDozier
Posting Expert
5,675 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 738
Skill Endorsements: 18
Let's look at what needs to be accomplished, forgetting the computer program. Focus on the algorithm.
Before : 1 2 3 4 5 6 7 8 9 10
After : 7 8 9 10 1 2 3 4 5 6
Pretend that you as a human being needed to do this. Pretend these are 10 blocks with numbers on them next to each other. How would you do it? Would you swap anything? Almost assuredly not. Here's what you would do.
- Create a spot large enough to hold blocks 7 through 10 if one does not already exist.
- Move blocks 7 through 10 out of the way. In other words, shove them somewhere TEMPORARILY so they were out of the way. In other words, put them where you cleared the space in step 1.
- Shove blocks 1 through 6 fours spaces right all at once.
- Shove blocks 7 through 10 where 1 through 4 used to be all at once.
- At this point, the space from step 1 is no longer needed.
That's what you would do as a human being. Make your program follow this.
- If a temporary array does not already exist, create one. In other words, declare an array statically that is large enough to handle the largest possible storage. If this is unknown, create it dynamically with the "new" command.
- Move blocks 7 to 10 to this temporary array using a loop, memmove, or memcpy.
- Move blocks 1 through 6 using a loop or memmove.
- Move blocks 7 to 10 where 1 through 4 were using memcpy, memmove, or a loop.
- If you created an array in step 1 with "new", "delete" it.
So you model your program after the way you'd explain step by detailed step to a person who didn't understand how to do it. It might be useful to actually create pieces of paper and number them and physically move them around first. Get the algorithm down before attacking the code. If you didn't need to "swap" when moving the papers around, you don't need to swap in the program. Look at what you do with the papers and make your loop follow that.
VernonDozier
Posting Expert
5,675 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 738
Skill Endorsements: 18