我正在尝试使用shell算法来安排[5] [5] [5]数组,到目前为止我可以打印整个数组但是当我运行shell()时它会打印相同的数组。它不会打印排列的数字。有什么帮助吗?
#include <iostream>
#include <stdlib.h>
using namespace std;
void ordShell(int numbers[5][5][5], int n);
void exchange(int& x, int& y);
int main()
{
int numbers[5][5][5] = {
{ {1,2,3,4,5}, {41,42,43,44,45}, {11,12,13,14,15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25} },
{ {26,27,28,29,30}, {31,32,33,34,35 }, {36,37,38,39,40}, {6,7,8,9,10}, {46, 47, 48, 49, 50}, },
{ {51, 52, 53, 54, 55}, {56,57,58,59,60}, {61,62,63,64,65}, {66, 67, 68, 69, 70}, {71, 72, 73, 74, 75}, },
{ {76, 77, 78, 79, 80}, {81,82,83,84,85}, {86,87,88,89,90}, {91, 92, 93, 94, 95}, {96, 97, 98, 99, 100}, },
{ {101, 102, 103, 104, 105}, {106,107,108,109,110}, {111, 112, 113, 114, 115}, {116, 117, 118, 119, 120}, {121, 122, 123, 124, 125} }
};
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
for(int l=0;l<5;l++)
{
cout<<numbers[i][j][l]<<",";
}
}}
cout<<"whatever"<<"";
cout<<"\n"<<"";
cout<<"NOW COMES SHELL"<<"";
ordShell(numbers,5);
cout<<"NUMBERS ARRANGED AFTER SHELL"<<"";
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
for(int l=0;l<5;l++)
{
cout<<numbers[i][j][l]<<",";
}
}}
return 0;
}
void ordShell(int numbers[5][5][5], int n)
{
int jump, i, j, k,j1,j2,k1,k2;
jump = n / 2;
while (jump > 0)
{
for (i = jump; i < n; i++)
{
j = i - jump;
j1= i - jump;
j2= i - jump;
while (j >= 0 )
{
k = j + jump;
k1 = j + jump;
k2 = j + jump;
if (numbers[j][j1][j2] <= numbers[k][k1][k2])
{j = -1; // arranged pair
j1 = -1;
j2 = -1;}
else
{
cout<<"exchange: "<<"";
cout<<numbers[j][j1][j2]<<" ";
cout<<numbers[k][k1][k2]<<"\n";
exchange(numbers[j][j1][j2], numbers[k][k1][k2]);
j -= jump;
j1 -= jump;
j2 -= jump;
}
}
}
jump = jump / 2;
cout<<"Jump: "<<jump<<"\n";
}
}
void exchange(int& x, int& y)
{
int aux = x;
x = y;
y = aux;
}
答案 0 :(得分:1)
你的函数中的问题非常简单:你不是修改数组而只修改它的副本:
void ordShell(int numbers[5][5][5], int n)//makes a copy of numbers
如果你想避免这个问题,你需要给你的函数指针。
但是,C ++方式是使用STL代替,所以你应该这样制作你的数组:std::vector<std::vector<std::vector<int> > >
(你可以在之后使用相同的初始化)
在你的函数中你只需要传递一个引用:
void ordShell(std::vector<std::vector<std::vector<int> > >& numbers, int n)
您还可以使用typedef
使变量名称更易于阅读:
typedef std::vector<std::vector<std::vector<int> > > vector3D
最后一件事,你不需要exchange
函数,std::swap
做同样的事情。