《编程珠玑》第三章

 1 int MAIN(vector x, int i, int n) 2 { 3     for (int ei = 0; ei < i; ei ++) 4         x = leftshift1(x, n); 5  6     return OK; 7 } 8  9 vector leftshift1 (vector & x, int n)10 {11     element first = x[0];12 13     for (int ei = 0; ei < n; ei ++)14         x[ei] = x[ei+1];15 16     x[n - 1] = first;17 18     return x;19 }

 1 int MAIN (vector x, int i, int n) 2 { 3     vector y = /*build vector with n elements*/ 4  5     //copy i elements from top x to y 6      memcpy(y, x, i * sizeof(x[0])); 7  8     //copy n-i elements from end x to y 9      memmove(x, x + i, (n - i) * sizeof(x[0]));10 11     //copy i elements from y to end x12      memcpy(x + (n - i), y,  i * sizeof(x[0]));13 14     return OK;15 }

 1 int MAIN (vector x, int i, int n) 2 { 3     x = reserveVector(x, 0, i-1); 4     x = reserveVector(x, i, n-1); 5     x = reserveVector(x, 0, n-1); 6  7     return OK; 8 } 9 10 vector reserveVector(vector & x, int startPos, int endPos)11 {12     int s = startPos;13     int e = endPos;14 15     while(s < e)16     {17         swap(x[s], x[e]);18         s ++;19         e --;20     }21 22     return x;23 }24 25  int swap (element & s, element & e)26 {27     element t = s;28     s = e;29     e = t;30     return OK;31 }

 1 int MAIN (vector x, int i, int n) 2 { 3     int s = 0; 4     int c = 0; 5     element f; 6  7     s = 0; 8     f = x[s]; 9 10     while (c < n)11     {12         //get final position of current element s13         int e = GetFinalPosition(s, i, n);14 15         //store original value in current position to tmp value16         element t = x[e];17 18         //fill current element s into final position19         x[e] = f;20 21         //increase count22         c ++;23 24         //prepare for next25         s = e;26 27         //store original value from tmp value28         f = t;29     }30 31     return OK;32 }33 34 int GetFinalPosition(int t, int i, int n)35 {36     if (t < i)37         return (n - i) + t;38 39     if ((t >= i) && (t < n))40         return (t - i);41 42     return t;43 }

posted on 2010-05-20 08:29 香依香偎孤旅独行的驿站 阅读(...) 评论(...) 编辑 收藏