Imagine if you had 2 arrays. One array is your original random array and the other is the output array.
Original:
Output:
| ?? | ?? | ?? | ?? | ?? | |
The question marks represent uninitialized space in memory.
Let us also have an index variable for each array for keeping track of progress:
1 2
|
int ind_orig = 0;
int ind_out = 0;
|
I am going to walk through the case of shifting to the right, so the final output should be:
I am going to use the same number, 7, that you mentioned in your example.
int_orig
is currently
0
, so we check to see if the first element of the original array is equal to 7.
12
is not equal to 7, so we assign
12
to the output array at the spot indexed by
ind_out
. We also increment both indexes. The next number at index
int_orig
is
13
, which does not equal 7. We repeat the same as earlier. Assign
13
to output array, and increment both indexes. Now we encounter a
7
, in this case
7
does equal 7. Only
ind_orig
is incremented, and nothing is done to the output array. This process continues until the end of the original array is reached. At that point the output array looks like this:
| 12 | 13 | 9 | ?? | ?? | |
Now all that is left to do is assign 0s until the end of output array is reached.
I hope this helps :)