【发布时间】:2015-02-06 00:12:14
【问题描述】:
我正在测量排序完成排序所需的步骤数,无论出于何种原因,冒泡排序似乎总是比插入排序快一点,根据我的阅读,它应该是相反的。
不会发布我的完整代码,但我相信问题可能在于我的计数在哪里。
冒泡排序:
public void sort()
{
for (out = nElems-1 ; out >= 1 ; out--)
{
count = count+1;
for (in = 0 ; in < out ; in++)
{
if ((a.get(in)) > (a.get(in+1)))
{
swap (in, in+1);
count = count+2;
}
}
}
}
插入排序:
void sort()
{
Integer temp[] = new Integer[1];
for (out = 1 ; out < nElems ; out++)
{
count = count+1;
temp[0] = a.get(out);
in = out;
while (in > 0 && a.get(in-1) >= temp[0])
{
a.set(in, a.get(in-1));
--in;
count = count+2;
}
a.set(in, temp[0]);
}
}
举个例子,我对 3 个文本文件进行了排序,其中填充了 2000 个随机整数,值介于 1-2000 之间,插入排序的平均值为 2,007,677 步,冒泡排序的平均值为 2,005,719。
【问题讨论】:
-
如何计算步数?您不应该计算进行比较的次数吗?或者可能是对数组的访问次数(读取或写入)?
-
是的,您在冒泡排序中缺少比较(最里面的 if,内部循环继续条件)。这只是两件事,我什至没有看过插入排序。
-
如果你有 count=count+2 用于交换,你不应该只用 count=count+1 进行单向转移吗?
-
@Thilo 抱歉,这就是我所说的步骤。对于 2000 个整数的文件,最好的情况是 2000,最坏的情况是 400 万(2000^2)。对于这两种类型。
-
好的,这让我更加困惑。对不起,伙计们,我是这个东西的新手。所以当你们谈论比较时,你们是在谈论 compareTo 吗?