數組迴圈左移

來源:互聯網
上載者:User

題:

對於有n個元素的數組 int a[n]={....};寫一個高效演算法將數組內容迴圈左移m位
比如: int a[6] ={1,2,3,4,5,6} ,迴圈左移3位得到結果{456123},
要求:
1不允許另外申請數組空間,但可以申請少許變數
2不允許採用每次左移

代碼:

#include <stdio.h>void ReverArrayN(int a[],int n, int k){int i;for( i=0; i<k/2; i++ )//三個for函數可以寫成一個函數的,其實{a[i] = a[i]^a[k-1-i];a[k-1-i] = a[i]^a[k-1-i];;a[i] = a[i]^a[k-1-i];}/*for( i=0; i<n; i++ ) { printf("%d ",a[i]); } printf("\n");*/for( i=k; i<(k+n)/2; i++ ){a[i] = a[i]^a[n-1-(i-k)];a[n-1-(i-k)] = a[i]^a[n-1-(i-k)];a[i] = a[i]^a[n-1-(i-k)];}/*for( i=0; i<n; i++ ) { printf("%d ",a[i]); } printf("\n");*/for( i=0; i<n/2; i++){a[i] = a[i]^a[n-1-i];a[n-1-i] = a[i]^a[n-1-i];a[i] = a[i]^a[n-1-i];}}  int main(int argc, char *argv[]) { int a[] = {1,2,3,4,5,6,7,8}; int i; ReverArrayN(a, sizeof(a)/sizeof(int), 3); for( i=0; i<sizeof(a)/sizeof(int); i++ ) { printf("%d ",a[i]); } return 0; }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.