【发布时间】:2011-11-08 14:19:55
【问题描述】:
这是我最初输入随机数然后使用插入排序方法对其进行排序的代码。
#include<iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(void)
{
int array[10];
srand (time(0));
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// inputting values into array[10]
{
array[i] = 1 + (rand()%100); //any random number between 1 - 100
}
cout <<" Before sorting " << " ---" <<endl;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )// printing the values
{
cout << array[i]<< endl;
}
int key ;
int t;//for future purpose
int compcount = 0;//to keep track of comparisons
for (int j = 1; j<sizeof(array)/sizeof(array[0]);j++)
{
key = array[j];//assign to second element initially
t = j-1;//assign to first element initially
while (j > 0 && array[t]>key)
{
array[t+1] = array[t];//moving array if bigger than next element
t = t-1;
compcount++;
}
array[t+1] = key;
}
cout << " After sorting" << " --- " <<endl;
for (int i = 0; i < sizeof(array)/sizeof(array[0]); i++ )
{
cout << array[i]<< endl;
}
cout << "comparison count is " << compcount << endl;
system ("pause");
return 0;
}
老实说,我有一个项目,它要求运行算法以获得最佳、最差和随机输入,并计算关键比较的次数(我认为在这段代码中是“compcount”)
现在随机输入对此有意义。当我用“一个已经排序的”数字数组(最好的情况)编写另一个代码时,键比较的次数为 0。 有人可以阐明最坏的情况是否正好相反?如果是这种情况,我尝试这样做,但我只得到了 32 次比较,而数组的大小为 32。
抱歉,问题太长了。 最坏情况输入应该有 (n^2-n)/2 比较次数对吗? 最好的情况应该是 n-1,因为只有第一个元素会遍历整个列表并确认它正在排序。我如何在代码中得到这个?
【问题讨论】:
-
谁给了你这个代码?你测试过吗?排序部分肯定不正确。
-
是的。我编写了这段代码并运行了它。它也工作得很好。
-
不,不是。见here。
-
您应该考虑更好地命名变量。
j > 0在您的内部 while 循环中的值是多少?我没有看到它在你的 for 循环之外被弄乱了,这意味着它应该总是正确的。 -
另外,您正在将比较作为 while 条件的一部分,这意味着您只计算成功比较,这就是为什么您的最佳案例结果是错误的。
compcount++也应该在 while 循环的正上方。
标签: c++ project insertion-sort