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

n 元一维向量旋转问题(编程珠机) 第二章问题B

2012-07-12 14:48 411 查看
/*
* method No_1
* using a temp to store x[0],then x[0] = x[i] ,x[i] = x[2i] ......until ki>=n,then x[(k-1)i] = x[0]
* then dealing with x[1],x[2] ........x[i-1]
*/

int gcd(int x ,int y)
{
if(x==0)return y;
if(y==0)return x;
if(x>y)return gcd(x%y,y);
return gcd(x,y%x);
}

void vector_reversal(char* str, int n, int rotdist)
{
int len = gcd(n,rotdist);
int i;
for(i =0;i<len;i++)
{
int temp = str[i];
int j = i;
while(1)
{
int k = j+rotdist;
if(k>=n)
k-=n;
if(k==i)
break;
str[j] = str[k];
j = k;
}
str[j] = temp;
}
}

/*
* method No_2
* recursive  the programming requirs that we can reversal vector ab into ba, so if len(a) < len(b),we can divide b into b1,b2,
* the vector will be ab1b2,and len(a) == len(b2),swap the memory a and b2,the vector changes to be b2b1a, and a has located at right
* place ,the next is to deal with b2b1,which is suposed be b1b2,so , it's  very easy to solve it with a recursive programme
* the method is same to dealing with len(a)<(len)b, when len(a) > len(b), and when len(a) == len(b) ,swap the memory
*/

void swap(char *p1_start,char *p2_start,int len)
{
while(len--)
{
char temp = p1_start[len];
p1_start[len] = p2_start[len];
p2_start[len] = temp;
}

}

void vector_reversal(char *base,int n, int i)
{
if(i == n-i)
{
swap(base,base+i,i);
return ;
}
if(i < n-i)
{
swap(base,base+n-i,i);
vector_reversal(base,n-i,i);
}
else{
swap(base+2*i-n,base+i,n-i);
vector_reversal(base,i,2*i-n);
}
}

/*
* methond No_3 , two times reversal
* the vector is ab,which is supposed to be changed into ba,
* so reverse a into a' , change b into b' ,then change (a'b') into (a'b')' = ba
*/
void swap(char *a,char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void reversal(char *start,char *end)
{
char *ptr_start = start;
char *ptr_end = end;
while(ptr_start < ptr_end)
{
swap(ptr_start,ptr_end);
ptr_start++;
ptr_end--;
}
}
void vector_reversal(char *base,int n, int i)
{
reversal(base,base+i-1);
reversal(base+i,base+n-1);
reversal(base,base+n-1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐