您的位置:首页 > 其它

原地矩阵转置算法实现

2012-09-27 17:34 148 查看
对于一个M*N的矩阵,现将其存储在一个一维数组中,数组长度 M*N,现要实现将该矩阵转置;

要求:

1、空间复杂度要求O(1);

算法实现:

#include <iostream>

using namespace std;

#define M 2
#define N 3
int arr[M*N] = {1,2,3,4,5,6};

void swap(int &a,int &b)
{
a=a^b;
b=a^b;
a=a^b;
}
void travase(int a[] , int x ) //数组起始地址,数组长度,数组 循环右移多少位
{
int i=0;
int j=x-1;
while(i<j)
swap(a[i],a[j]),i++,j--;

}
void movedata(int a[] ,int x)
{
if(x == 1 )
return ;
travase(a,x-1);
travase(a,x);
}
void transposeInpalce()
{
int from , to, offset ,step;
int i,j;
step = N;
to=offset = 0;
for(i=0; i< N ;i++)
{
for( j=0 ,from = i+offset; j<M ;j++)
{
movedata(arr+to,from-to+1);
from += step;
to++;
}
step--;
offset += M-1;
}
}
void print()
{
int i=0;
for(i=0;i<M*N;i++)
cout<<arr[i]<<" ";
cout<<endl;
}

int main()
{
cout << "Hello world!" << endl;
print();
transposeInpalce();
print();
return 0;
}


转置的思想来源:http://www.qiyeku.com/xinwen/1182832.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 存储 im