我试图找出是否使用sentinal-terminated序列对数组进行排序。
在尝试我尝试检查数组是升序,降序还是未分类时。
#define isNaN(X) (X != X)
#define NaN std::numeric_limits<float>::quiet_NaN()
enum sortType { ASCENDING, DESCENDING, UNKNOWN, UNSORTED };
我认为我的bool inSorted函数中存在错误,我认为问题在于检查最后的NaN值。
bool isSorted(const float data[], const int currentDataItem, const sortType typeOfSort) {
switch(typeOfSort) {
case ASCENDING:
if(currentDataItem == 0){
return isSorted(data, (currentDataItem + 1), ASCENDING);
} else if(data[currentDataItem] > data[currentDataItem+1]){
return false;
} else if(data[currentDataItem] == data[currentDataItem]){
return isSorted(data, (currentDataItem+1), ASCENDING);
} else {
return true;
}
case DESCENDING:
if(currentDataItem == 0){
return isSorted(data, (currentDataItem + 1), DESCENDING);
} else if(data[currentDataItem] < data[currentDataItem+1]){
return false;
} else if(data[currentDataItem] == data[currentDataItem]){
return isSorted(data, (currentDataItem+1), DESCENDING);
} else {
return true;
}
}
}
然后通过bool排序
调用isSortedbool sorted(const float data[]) {
bool ascending = isSorted(data, 0, ASCENDING);
bool descending = isSorted(data, 0, DESCENDING);
if(!ascending && !descending){
return false;
}
return true;
}
由主
包裹int main(const int argc, const char* const argv[]) {
float data[] = {1, 2, 4, 5, 6, NaN};
if (sorted(data))
cout << "Data is sorted" << endl;
else
cout << "Data is not sorted" << endl;
return 0;
}
答案 0 :(得分:0)
实现递归函数时,您需要明确地问自己以下问题:
数目:
因此:
case ASCENDING:
// Empty list
if (std::isnan(data[currentDataItem]))
return true;
// One element list.
else if (std::isnan(data[currentDataItem + 1])
return true;
// Recursive case: we've found a location where the data isn't sorted.
else if (data[currentDataItem] > data[currentDataItem + 1])
return false;
// This location is sorted, check the next location.
else
return isSorted(data, currentDataItem + 1, typeOfSort);
请注意,我只在基本情况下直接return true;
。否则,我们要么失败了,要么递减。