问题描述
我正在从事一个项目,该项目要求我们实现不同的排序并添加计数器变量以测量具有不同数组大小的运行时。我的问题是我当前的输出与插入排序的预期输出不匹配。
对错误有什么建议吗?
输出:
Array Size: 10 100 1000 10000
--------------------------------------------------------------------
Insertion sort 41 2605 242934 25053573
预期输出:
Array Size 10 100 1000 10000
Insertion Sort | 38 | 2600 | 242928 | 25053566
数组大小为 10 的数组内容是什么
Insertion sort
[ 935,942,697,299,382,579,408,181,366,505 ] //unsorted
[ 181,505,935,942 ] //sorted
template<class ItemType>
int insertionsort(ItemType theArray[],int n) {
int counter = 0; //keeps track of number of comparisons
for (int unsorted = 1; unsorted < n; unsorted++) {
ItemType nextItem = theArray[unsorted];
int loc = unsorted;
counter++;//increment here
while ((loc > 0) && (theArray[loc - 1] > nextItem)) {
//removed this after comment suggested it
//if(theArray[loc - 1] > loc){
counter++; //increment here
//}
theArray[loc] = theArray[loc - 1];
loc--;
}
theArray[loc] = nextItem;
}
return counter;//returns the number of comaparisons
}
int* makeRandomArray(int n,int seed) {
srand(seed);
int * a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = rand() % 1000;
}
return a;
}
int main(){
const int seed = 9000;
/******************************/
/* Start of Insertion Sort */
/******************************/
std::cout << "Insertion sort";
n = 10;
int* a;
a = makeRandomArray(10,seed);
std::cout <<std::setw(13)<< insertionsort(a,n);
delete[] a;
n = 100;
a = makeRandomArray(100,n);
delete[] a;
n = 1000;
a = makeRandomArray(1000,n);
delete[] a;
n = 10000;
a = makeRandomArray(10000,n)<<std::endl;
delete[] a;
}
#endif
解决方法
您的计数(counter++;
与比较不同步。
我将计数移至比较和 got the desired result 之前。
template<class ItemType>
int insertionsort(ItemType theArray[],int n) {
int counter = 0; //keeps track of number of comparisons
for (int unsorted = 1; unsorted < n; unsorted++) {
ItemType nextItem = theArray[unsorted];
int loc = unsorted;
// remove this
//counter++;//increment here
// add counter++ just before the comparision
while ((loc > 0) && (counter++,theArray[loc - 1] > nextItem)) {
if(theArray[loc - 1] > loc){
// remove this
//counter++; //increment here
}
theArray[loc] = theArray[loc - 1];
loc--;
}
theArray[loc] = nextItem;
}
return counter;//returns the number of comaparisons
}
请注意,rand()
返回的内容取决于环境,因此在不同环境下结果可能不同。