Circular Shift in an Array
Let an Array is of n elements. You are asked to shift elements in a circular way in left or right direction.
Array=[12,13,14,15,16];
here n=5.
if shifting element s=2,
Left shifting will result in [14,15,16,12,13],
Right shifting will result in [15,16,12,13,14].
I am only going to show the left circular shift.
First solution:
Store left most element in a variable,then left shift whole array,push the stored element at the end of the array.
Do this process s times.
Costly solution because n number of shifting is required for s times.
Second solution:
Storing index (s+1) to n of a[] are copied to a new array Na[14,15,16,0,0]
int k=s+1;
loop(i,1,n-s)
{
Na[i]=a[k];
k++;
}
Storing index 1 to s of a[] are copied to a new array Na[14,15,16,12,13]
k=1;
loop(i,n-s+1,n)
{
Na[i]=a[k];
k++;
}
Third solution:
It's Mathematical solution. Be careful for index mapping
if s=2
i---->j
1--->4
2--->5
3--->1
4--->2
5--->3
if s=3
i---->j
1--->3
2--->4
3--->5
4--->1
5--->2
From this mapping we conclude that: j=(i+(n-d-1))%n+1
loop(i,1,n)
{
int j=(i+(n-d-1))%n+1;
Na[j]=a[i];
}
So for d=2, Na=[14,15,16,12,13].
It's Done. Now it's your turn to optimize it for right shifting. :)
Array=[12,13,14,15,16];
here n=5.
if shifting element s=2,
Left shifting will result in [14,15,16,12,13],
Right shifting will result in [15,16,12,13,14].
I am only going to show the left circular shift.
First solution:
Store left most element in a variable,then left shift whole array,push the stored element at the end of the array.
Do this process s times.
Costly solution because n number of shifting is required for s times.
Second solution:
Storing index (s+1) to n of a[] are copied to a new array Na[14,15,16,0,0]
int k=s+1;
loop(i,1,n-s)
{
Na[i]=a[k];
k++;
}
Storing index 1 to s of a[] are copied to a new array Na[14,15,16,12,13]
k=1;
loop(i,n-s+1,n)
{
Na[i]=a[k];
k++;
}
Third solution:
It's Mathematical solution. Be careful for index mapping
if s=2
i---->j
1--->4
2--->5
3--->1
4--->2
5--->3
if s=3
i---->j
1--->3
2--->4
3--->5
4--->1
5--->2
From this mapping we conclude that: j=(i+(n-d-1))%n+1
loop(i,1,n)
{
int j=(i+(n-d-1))%n+1;
Na[j]=a[i];
}
So for d=2, Na=[14,15,16,12,13].
It's Done. Now it's your turn to optimize it for right shifting. :)
Comments
Post a Comment