按位置旋轉一維數組演算法

來源:互聯網
上載者:User

 

一種一維數組按從第i個位置“旋轉”,例如abcdefgh, i = 3,則旋轉後變為defghabc

Code:
  1. /*  
  2.   rotate a one-dimensinal vector of n elements left by i positions. For instance,  
  3.   with n=8 and i=3, the vector abcdefgh is rotated to defghabc. Simple code uses an  
  4.   n-element intermediate vector to do the job in n steps. Can you rotate the vector  
  5.   in time proportional to n using only a few dozen extra bytes of storage.  
  6. */  
  7. #include <iostream>   
  8. using namespace std;   
  9. void rotate(const int length, const int pos, int * vec);   
  10. void reverse(int *vec, int beg, int end);   
  11. int main()   
  12. {   
  13.     int test[] = {1,2,3,4,5,6,7};   
  14.     rotate(7,7,test);   
  15.     for(int i = 0; i<= 6; i++)   
  16.     {   
  17.         cout<<test[i]<<endl;   
  18.     }   
  19. }   
  20.   
  21. //採用3此倒序數組的方法rotate.   
  22. void rotate(const int length, const int pos, int * vec)   
  23. {   
  24.     reverse(vec, 0, pos-1);   
  25.     reverse(vec,pos,length-1);   
  26.     reverse(vec,0, length-1);   
  27. }   
  28.   
  29. //倒排一個數組   
  30. void reverse(int *vec, int beg, int end)   
  31. {   
  32.     int sum = beg+end;   
  33.     int tmp;   
  34.     for(int i = beg; i<= (beg+end)/2; i++)   
  35.     {   
  36.         tmp = vec[i];   
  37.         vec[i] = vec[sum-i];   
  38.         vec[sum-i] = tmp;   
  39.     }   
  40. }   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.