Algorithm exercises---Arrays of linear tables for cyclic movement

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.