【问题标题】:The Output of the code is not coming as expected代码的输出未按预期进行
【发布时间】:2019-05-20 07:41:00
【问题描述】:

我正在尝试使用 heapsort 对类哈希表的对象进行排序

struct hashmap{
        int key;
        int value;   };


vector<hashmap> heap;
int n;
void heapify(int i)
{
    int l,r,max=i;
    l=2*i+1;
    r=2*i+2;
    if((heap[r].key>heap[max].key)||((heap[r].key=heap[max].key)&&(heap[r].value>heap[max].value)))
    {
       max=r;
    }
    else if((heap[l].key>heap[max].key)||((heap[l].key=heap[max].key)&&(heap[l].value>heap[max].value)))
    {
        max=l;
    }

    if(max!=i)
    {
    swap(heap[max],heap[i]);
    heapify(max);
    }
}

void heapsort()
{
    for (int i=n/2-1;i>=0;i--) 
        heapify(i); 

    while(n>0)
    {
        swap(heap[n-1],heap[0]);
        --n;
        heapify(0);             
    }
}
int main()
{
    cout<<"Enter the no of elements : ";
    cin>>n;
    Det(n);
    heapsort();
    display();
    return 0;
}

如果我的输入是 (1,3) (2,5) (1,2) 我的预期输出应该是 (1,2) (1,3) (2,5) 但这不是我的我得到了。我得到了一些随机数作为输出。

【问题讨论】:

  • 您能否添加一个main 函数来重现您的问题?
  • 注意=和==之间的区别。
  • 您的变量 n 已初始化,但您没有给它任何值,这意味着它具有随机值。然后你在 heapsort 上做所有的循环。这对我来说听起来有点奇怪
  • @DrosvarG 全局变量默认初始化为0。这正是问题所在。 heapsort 对 n == 0 没有任何作用。
  • if 内部的这个任务是故意的吗? (heap[r].key = heap[max].key)

标签: c++ recursion vector hashmap heapsort


【解决方案1】:

假设您想先按键排序,然后按值排序,您也可以将std::sort 与比较函数一起使用:

struct hashmap{
   int key;
   int value;
};

bool comp(const hashmap& a, const hashmap& b) {
    return tie(a.key, a.value) < tie(b.key, b.value);
}

int main()
{
  vector<hashmap> v{
       {1, 3}
     , {2, 5}
     , {1, 2}
  };

  sort(v.begin(), v.end(), comp);

  for (const auto& h : v) {
    cout << '(' << h.key << ',' << h.value << ')';
  }
  cout << endl;
  return 0;
}

【讨论】:

  • 您是否将所有函数声明为带有 lambda 的 function 变量? function&lt;bool(const hashmap&amp; a, const hashmap&amp; b)&gt; comp = [](const hashmap&amp; a, const hashmap&amp; b) 似乎比 bool comp(const hashmap&amp; a, const hashmap&amp; b) 工作更多,而且恕我直言,可读性也较差。
  • @R0m1 但是使用 std::sort 可以吗?或者是否有可能通过不使用 std::sort 来防止出错?
  • @Bad_Panda 就个人而言,我宁愿使用 std::sort 而不是我可以自己编写的任何排序算法,原因很简单,编写一个好的排序算法可能非常棘手。除非我在这里遗漏了什么,否则我没有理由不使用它。
【解决方案2】:

我认为您的堆排序函数中不需要 while 循环。像下面这样调用就足够了:

void heapsort()
{
    for (int i=n/2-1;i>=0;i--) 
        heapify(i); 
}

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 2018-12-23
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多