我想添加compare++
到此代码中,以计算此算法完成了多少比较。是否需要在第一个 while 循环中和while内的compare
每次执行时增加计数?这些是唯一应该增加的位置吗?(我在我认为属于的地方添加了这个增量并注释掉。请忽略交换功能)Merge(...)
if
else
compare
#include "MergeSort.h"
template<class ItemType>
void MergeClass<ItemType>::sort(ItemType values[], int first, int last)
// Post: The elements in values are sorted by key.
{
if (first < last)
{
int middle = (first + last) / 2;
sort(values, first, middle);
sort(values, middle + 1, last);
Merge(values, first, middle, middle + 1, last);
}
}
template<class ItemType>
void MergeClass<ItemType>::Merge(ItemType values[], int leftFirst, int leftLast,
int rightFirst, int rightLast)
// Post: values[leftFirst]..values[leftLast] and
// values[rightFirst]..values[rightLast] have been merged.
// values[leftFirst]..values[rightLast] are now sorted.
{
ItemType tempArray[5];
int index = leftFirst;
int saveFirst = leftFirst;
while ((leftFirst <= leftLast) && (rightFirst <= rightLast))
{
if (values[leftFirst] < values[rightFirst])
{
tempArray[index] = values[leftFirst];
leftFirst++;
//compare++;
}
else
{
tempArray[index] = values[rightFirst];
rightFirst++;
//compare++;
}
index++;
//compare++;
}
while (leftFirst <= leftLast)
// Copy remaining items from left half.
{
tempArray[index] = values[leftFirst];
leftFirst++;
index++;
}
while (rightFirst <= rightLast)
// Copy remaining items from right half.
{
tempArray[index] = values[rightFirst];
rightFirst++;
index++;
}
for (index = saveFirst; index <= rightLast; index++)
values[index] = tempArray[index];
}
template<class ItemType>
inline void MergeClass<ItemType>::Swap(ItemType& item1, ItemType& item2)
// Post: Contents of item1 and item2 have been swapped.
{
ItemType tempItem;
tempItem = item1;
item1 = item2;
item2 = tempItem;
}
template<class ItemType>
MergeClass<ItemType>::MergeClass()
{
compare = 0;
swap = 0;
}
template<class ItemType>
void MergeClass<ItemType>::sortPreformance()
{
cout << "Comparisons made: " << compare <<endl;
cout << "Swaps made: "<< swap <<endl;
}