【问题标题】:Have issues determining if array is sorted在确定数组是否已排序时遇到问题
【发布时间】:2018-04-10 23:50:29
【问题描述】:

我试图确定一个数组集是否使用前哨终止序列进行排序。

在尝试中,我尝试检查数组是升序、降序还是未排序。

#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;
      }
    }
  }

isSorted 然后被 bool sorted 调用

bool sorted(const float data[]) {
  bool ascending = isSorted(data, 0, ASCENDING);
  bool descending = isSorted(data, 0, DESCENDING);

  if(!ascending && !descending){
    return false;
  }
  return true;
}

由 main 总结

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;
}

【问题讨论】:

  • 使用std::isnan 而不是宏ffs。
  • 奇怪,我没有看到 OP 代码中使用的宏...
  • 寻找你是否到达终结者的地方。
  • 我建议使用 for/while 循环而不是递归。对数组进行递归可能会很快填满您的堆栈。
  • 所有代码都是 1-liner -- std::is_sorted(data, std::find(data, std::end(data), std::isnan));。如果你想降序排序,另一个 1-liner,只需将 std::greater&lt;float&gt; 作为第三个参数添加到 is_sorted

标签: c++ arrays sorting recursion


【解决方案1】:

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

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

答案:

  1. 如果当前数组位置与 NaN 进行比较,则我们已排序。
  2. 如果我们的位置没有排序,我们知道列表没有排序。如果我们的位置已排序,则如果递归条件在下一个对上成立,则数组将被排序。

因此:

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

【讨论】:

  • 感谢您的帮助!这更有意义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-28
  • 1970-01-01
  • 2017-08-08
  • 2013-11-22
相关资源
最近更新 更多