确定数组是否已排序有问题

时间:2017-10-30 03:35:00

标签: c++ arrays sorting recursion

我试图找出是否使用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排序

调用isSorted
bool 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;
}

1 个答案:

答案 0 :(得分:0)

实现递归函数时,您需要明确地问自己以下问题:

  1. 递归函数的基本情况是什么?
  2. 递归函数的递归情况是什么?
  3. 数目:

    1. 如果当前数组位置与NaN进行比较,那么我们将进行排序。
    2. 如果我们的位置没有排序,我们知道列表没有排序。如果我们的位置已经排序,那么如果递归条件适用于下一对,则对数组进行排序。
    3. 因此:

      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;。否则,我们要么失败了,要么递减。