以下面的代碼到:如何將計數器添加到氣泡排序來計算數量比較?
int CountBubbleSort=0;
template <typename Comparable>
void bubbleSort(vector<Comparable*> &v)
{
bool sorted = false;
for(int pass = 1; pass < v.size() && !sorted; pass++)
{
sorted = true;
for(int i = 0; i < v.size() - pass; i++)
{
if(*v[i + 1] < *v[i])
{
swap(v, i, i + 1);
CountBubbleSort++;
sorted = false;
}
}
}
cout<<"bubbleSort comparison is "<<CountBubbleSort<<endl;
}
當我打電話的功能,爲什麼是CountBubbleSort
「0」的輸出,是什麼問題?
您的輸入是否已經排序?你不計算比較次數,你要計算掉期次數。 – molbdnilo