我很难把这个伪码翻译成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;
}发布于 2013-10-27 16:57:52
伪代码与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-27 16:49:39
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];也不会像你想的那样工作(见上面!)
https://stackoverflow.com/questions/19620564
复制相似问题