Article Directory
topic
Assuming that n (n>1) integers are stored in a one-dimensional array R, design an algorithm that is as efficient as possible in terms of time and space. Move the sequence saved in R to the left by p (0<p<n) positions, that is, transform the data in R from (x0,x1,x2,…,xn-1) to (xp,xp+1,…, xn+1,x0,x1,...,xp-1), requires:
- The basic design idea of the algorithm is given.
- According to the design idea, the algorithm is implemented in C/C++, and comments are given at the key points.
- Explain the time complexity and space complexity of the algorithm.
Basic Design Ideas
- Based on the above requirements, it is analyzed that the title mainly requires that the elements in the array R be cyclically shifted to the left by p bits, and return to the realized array.
- Therefore, in the first step, we can first consider reversing all the elements in the array R to obtain the array (xn-1, xn-2,..., x2, x1, x0).
- Next, reverse the first np elements in the array R to obtain the array (xp,xp+1,...,xn-1,xp-1,xp-2,...x2,x1,x0).
- Then, reverse the last p elements in the array R to get the array (xp, xp+1,...,xn-1, x0, x1,...,xp-1) required by the title.
Code
Array LinearList::Reverse(int left,int right)//传入顺序表arr逆置的左右临界
{
if(arr.length <= 1)
return arr;
int i = left,j = right-1;//设置哨兵i,j分别指向左右临界的下标
int temp = 0;
while(i < j) //交换哨兵指向的元素位置
{
temp = arr.data[i];
arr.data[i++] = arr.data[j];
arr.data[j--] = temp;
temp = 0;
}
return arr;
}
Array LinearList::Question_10(int p)
{
if(arr.length <=1)//判断非法数组长度
return arr;
cout<<"Move "<<p<<" bit left"<<endl;
Reverse(0,arr.length); //逆置数组R中的全部元素
Reverse(0,arr.length-p); //逆置数组R中前n-p个元素
Reverse(arr.length-p,arr.length); //逆置数组R中后p个元素
return arr;
}