我測量排序完成排序所需的步驟數,無論出於何種原因,氣泡排序總是比插入排序快一點,從我讀的內容來看,它應該是相反的方式。Java - 爲什麼我的Bubble排序比我的插入排序更快?
不會發布我的完整代碼,但我相信這個問題可能與我有我的位置有關。
冒泡排序:
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]);
}
}
,只是舉個例子,我整理充滿了2000的隨機整數3個文本文件的值,從1- 2000年,插入排序的平均值爲2,007,677步,而冒泡排序的平均值爲2,005,719。
你如何計算步驟?你不應該計算正在進行的比較次數嗎?或者可能訪問數組的數量(讀或寫)? – Thilo 2015-02-06 00:14:34
是的,你在氣泡排序中缺少比較(最裏面的if,內部循環延續條件)。這只是兩件事,我甚至沒有看過插入排序。 – lared 2015-02-06 00:16:26
如果您有交換的count = count + 2,您是否應該爲單向傳輸計數= count + 1? – Joffan 2015-02-06 00:17:11