将伪代码转换为C ++

时间:2013-10-27 16:43:10

标签: c++ algorithm sorting

我很难将这个伪代码转换为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;
}

2 个答案:

答案 0 :(得分: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];

不会按照您的意图行事(见上文!)。

答案 1 :(得分: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
相关问题