【发布时间】:2014-11-18 21:32:48
【问题描述】:
我目前正在处理一项任务,该任务要求我们实现几种不同的排序并引入计数器变量来测量运行时间。
我的问题是,我对是否将某些“操作”作为会增加我的计数器的内容感到困惑。例如,我的教科书是这样说的:
....
所以,据我了解,我应该计算“比较”,但我不明白这是否适用于 if 语句、while 循环等。
例如,这是我的插入排序。
float insertionSort(int theArray[], int n) {
float count = 0;
for (int unsorted = 1; unsorted < n; unsorted++) {
int nextItem = theArray[unsorted];
int loc = unsorted;
while ((loc > 0) && (theArray[loc - 1] > nextItem)) {
theArray[loc] = theArray[loc - 1];
theArray[loc] = nextItem;
loc--;
count += 4;
}
}
return count;
}
如您所见,对于 while 循环的每次迭代,我将 count 增加 4。我认为,这确实突出了我的问题。
我的推理是,我们在while循环的条件语句中做了两个比较:
(loc > 0 && theArray[loc - 1] > nextItem)
然后,我们在数组中进行两次移动。根据我的理解,这意味着我们已经执行了 4 个“操作”,我们会将 counter 增加 4,以便在执行结束时测量运行时间。
这是正确的吗?非常感谢您的帮助。
【问题讨论】:
标签: c++ algorithm sorting runtime big-o