One: The problem
To store N (n>1) integers in a one-dimensional array R, try to design an algorithm that is as efficient as possible in both time and space, moving the saved sequence in R to the left p (0<p< N) a position,
That is, the data series in R is transformed from (x0,x1,...,xn-1) to (xp,xp+1, ..., xn-1, x0,x1,...,x).
Second: Thinking
In order to implement the r in the sequence of the left shift p position, just first the first P elements in the r inverse, and then the rest of the elements are reversed, and finally all the elements of R to do an inverse operation of the whole, the algorithm described as follows:
(i) Step one: reverse the first P elements
(ii) Step two: reverse the P elements
(iii) Step three: Reverse all elements (Implementation)
Three: Code implementation
voidReverse (intR[],intLintR) { intI, J; inttemp; for(i = l, j = R; i < J; i++,j--) {Temp=R[i]; R[i]=R[j]; R[J]=temp; }}voidMovel (intR[],intNintp) { if(P <=0|| P >=N)return; Reverse (R,0, P-1); Reverse (R, p, n-1); Reverse (R,0N1);}
intMain () {inta[7] = {1,2,3,4,5,6,7 }; Movel (A,7,3); for(inti =0; I <7; i++) printf ("%d", A[i]); System ("Pause"); return 0;}
Four: Performance analysis
Time complexity is O (n), space complexity is O (1)
V: Add---right shift
void MoveR (intintint p) { if0 | | p >= n) return; 0 1 ); 0 1 ); 1 );}
Six: Summarize left and right shifts(a) left shift: the first P elements in R are reversed, leaving the inverse, the overall inverse(b) Right shift: Overall reverse, front p reverse, rear p reverse
Algorithm exercises---Arrays of linear tables for cyclic movement