0

我很难将这个伪代码翻译成 C++。目标是在 A[] 中生成随机数并使用插入排序对它们进行排序,然后以毫秒为单位获取执行时间。插入排序将运行 m=5 次。每个 n 值应为 100、200、300、....、1000。因此,例如,如果 n=100,那么它将使用 5 组不同的随机数运行 5 次,然后对 n=200 执行相同的操作,等等...

我已经写了我的插入排序并且它有效,所以我没有包括它。我真的很难将这个伪代码翻译成我可以使用的东西。我包括了我的尝试和伪代码,以便您进行比较。

伪代码:

main()
//generate elements using rand()
for i=1 to 5
   for j=1 to 1000
      A[i,j] = rand()

//insertion sort
for (i=1; i<=5; i=i+1)
   for (n=100; n<=1000; n=n+100)
      B[1..n] = A[i,n]
      t1 = time()
      insertionSort(B,n)
      t2 = time()
      t_insort[i,n] = t2-t1

 //compute the avg time
 for (n=100; n<=1000; n=n+100)
    avgt_insort[n] = (t_insort[1,n]+t_insort[2,n]+t_insort[3,n]+...+t_insort[5,n]+)/5
 //plot graph with avgt_insort

这是我的尝试:

我对 t_insort 和 avgt_insort 感到困惑,我没有将它们写入 C++。我要把这些做成新的数组吗?我也不确定我是否正确地做我的时间。我在这个运行时有点新,所以我还没有真正把它写成代码。

#include <iostream>
#include <stdlib.h>
#include <time.h>

int main()
{   
int A[100];
for(int i=1; i<=5; i++)
{
    for(int j=1; j<=1000; j++)
    {
        A[i,j] = rand();
    }
}

for(int i=0;i<=5; i++)
{
    for(int n=100; n<=1000; n=n+100)
    {
        static int *B = new int[n];
        B[n] = A[i,n];
        cout << "\nLength\t: " << n << '\n';
        long int t1 = clock();
        insertionSort(B, n);
        long int t2 = clock();

                    //t_insort 

        cout << "Insertion Sort\t: " << (t2 - t1) << " ms.\n";
    }
}
for(int n=100; n<=1000; n=n+100)
{
    //avt_insort[n]
}
return 0;
}
4

2 回答 2

1

A[i,j]A[j](逗号运算符!)相同,并且不起作用。

您可能想要声明一个二维数组,A甚至更好std::array

int A[100][1000];

std::array<std::array<int,1000>, 100> A; // <- prefer this for c++

同样在 for 循环内立即分配B看起来也不正确:

static int *B = new int[n];

B[n] = A[i,n];

也不会按您的意愿工作(见上文!)。

于 2013-10-27T16:49:39.197 回答
1

伪代码相对接近于 C++ 代码,但有一些语法变化。请注意,此 C++ 代码是一个简单的“翻译”。更好的解决方案是使用 C++ 标准库中的容器。

int main()
{
  int A[6][1001], B[1001]; //C++ starts indexing from 0
  double t_insort[6][1000]; //should be of return type of time(), so maybe not double
  int i,j,n;
for( i=1;i<=5;i++)     //in C++ it is more common to start from 0 for(i=0;i<5;i++)
   for(j=1;j<=1000;j++)
      A[i][j] = rand();  //one has to include appropriate header file with rand()
                         //or to define his/her own function
for (i=1; i<=5; i++)
  for (n=100; n<=1000; n=n+100)
  {
    B[n]=A[i][n];
    t1 = time(); //one has firstly to declare t1 to be return type of time() function
    insertionSort(B,n); //also this function has to be defined before
    t2=time();
    t_insort[i][n]=t2-t1; //this may be necessary to change depending on exact return type of time()
  }
}

for (n=100; n<=1000; n=n+100)
  for(i=1;i<=5;i++)
    avgt_insort[n] += t_insort[i][n]

avgt_insort[n]/=5;
 //plot graph with avgt_insort
于 2013-10-27T16:57:52.190 回答