【发布时间】:2014-06-02 06:54:33
【问题描述】:
我试图找出这两种算法执行所花费的实际时间,并且我发现与互联网上许多地方的信息不一致,这些信息表明插入排序更好。然而,我发现冒泡排序执行得更快。我的代码如下。
冒泡排序
for(int j = 0; j < a.length - 1; j++){
for(int i = 0; i < a.length - 1 - j; i++) {
count++;
if(a[i] > a[i+1]){
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
插入排序
for(int i = 1; i < a.length; i++){
for(int j = i - 1; j >= 0; j-- ){
if(a[j] > a[i]) {
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
我是这样计算开始和结束时间的。
long startTime = System.currentTimeMillis();
.....your program....
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime);
我发现,对于插入排序,10 次运行的平均时间为 13,而对于冒泡排序,它仅为 5。对此有什么解释吗?
【问题讨论】:
-
那不是插入排序。它甚至不是一种:ideone.com/aFCPft
-
那个插入排序看起来很像selection sort。您应该阅读Insertion sort 并实现该算法。
标签: algorithm sorting runtime bubble-sort insertion-sort