移调1维数组数组

2023-09-11 04:32:21 作者:犯二吃啥药好呢

所以我有一个一维数组的N值,其中N是一个完美的正方形。我想象这一维阵列作为二维阵列(尽管它不是)。例如,值的数组 int数组= {0,1,2,3,4,5,6,7,8}

So I have a ONE dimensional array with N values, where N is a perfect square. I visualize this one dimensional array as a two dimensional array (although it is not). For example, an array with values int Array = { 0,1,2,3,4,5,6,7,8 }

这是

int *Array = new int [9];                                                                                                                                                                                                    
for ( int i = 0 ; i < 9 ; i ++ )
         Array[i] = i; // For example

这是打印为

0 1 2
3 4 5 
6 7 8

所以,我想交换的一维数组这样的立场是,我得到了它的转置,...

So, I want to interchange the position in the one dimensional array such that I get the transpose of it,...

例如...

0 3 6
1 4 7
2 5 8

这是基本一致的一维数组,但在的值交换,这样的数组现在 int数组= {0,3 ,6,1,4,7,2,5,8}

This is basically the same one dimensional array , but the values are swapped such that the array is now int Array = {0,3,6,1,4,7,2,5,8}

如果我是把它扩展到维数组1024 * 1024,如何将逻辑是什么?

If I were to scale it to an array of dimension 1024*1024, how will the logic be ?

推荐答案

通过 N =开方(N),你可以只尝试一些简单的,如:

With n = sqrt(N), you could just try something simple like:

for(int i = 0; i < n; ++i)
    for(int j = i+1; j < n; ++j)
        std::swap(Array[n*i + j], Array[n*j + i]);