您的位置:首页 > 编程语言

数组循环移动代码,只使用一个临时变量

2009-09-21 18:43 337 查看
算法原理:假如要将数组循环左移i位,则先将数组前i位逆置,再将后n-i位逆置,最后将整个数组逆置。逆置也有小技巧:使用两个游标start、end,将子数组的第一个元素和子数组的最后一个元素交换,然后start++,end--。

#include<iostream>
using namespace std;
void reverse(char *ch,int start,int end)
{
while(start <= (start+end)/2)
{
cout<<"ch[start]="<<ch[start]<<" "<<"ch[end]"<<ch[end]<<endl;
char temp;
temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
++start;
--end;
}
}
int main()
{
char ch1[9] = "abcdefgh";
for(int t = 0;t != 8;++t)
cout<<ch1[t];
cout<<endl;
cout<<"你要将数组左移几位?";
int i;
cin>>i;
reverse(ch1,0,i-1);
for(int t = 0;t != 8;++t)
cout<<ch1[t];
cout<<endl;
reverse(ch1,i,7);
for(int t = 0;t != 8;++t)
cout<<ch1[t];
cout<<endl;
reverse(ch1,0,7);
for(int t = 0;t != 8;++t)
cout<<ch1[t];
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐