如果你想有一个冒泡排序算法显着最佳的变化,最差,平均情况下效率,试试这个:
int count = n - 1; // The input size
bool sFlag = true; // A flag variable allowing the inner outerloop to
break early and fall through
while (sFlag){
sFlag = false; // Set false so that the loop can break if no swaps occur
for (int j = 0; j < count; j++){
if (A[j+1] < A[j]){
int temp; // Swap the two elements
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
sFlag = true; // A swap has occured, iterate again
}
}
count--; //Next time, don't bother looking at the last element, it is
in order
}
这种最坏的情况是Cworst(N)= 1/2N (n + 1),最好的情况是Cbest(n)= n-1。 这是因为count变量会根据已经完成的迭代量相对于输入大小而使内部循环迭代次数减少。
这是我迄今为止遇到的最有效的气泡排序。
到目前为止您提出了什么? – 2013-03-06 14:50:36
非常多的声音,你想我们为你的作业制定一个答案 – 2013-03-06 14:50:38
气泡排序复杂性讨论是非常普遍的网络,我没有看到任何人都会有问题,除非它是作业。尝试谷歌搜索“泡沫排序的复杂性”? – 2013-03-06 14:52:29