c++ - 将伪代码翻译成 C++

标签 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;
}

最佳答案

伪代码相对接近 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

关于c++ - 将伪代码翻译成 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620564/

相关文章:

algorithm - 在数百万用户编辑的音频文件中查找重复内容(音频内容散列)

Javascript 递归

javascript - 通过可汗学院在javascript中进行选择排序

php 使用下划线对文件名进行排序

ios - 根据数据对数组进行排序

c++ - 使用 STL 容器的部分 C++ 模板特化

c++ - <void(void)> 在模板参数中的含义

c++ - 使用 pugiXml 读取 XML 文档

pandas - 我想在列上使用 lambda 将 DataFrame 拆分为 2 个 df

c++ - 为什么非类型模板参数表达式处理在编译器之间不一致?