简体   繁体   English

插入排序链表C ++

[英]Insertion sort linked list c++

I'm trying to sort a filled linked list with random numbers. 我正在尝试使用随机数对填充的链表进行排序。 The function I have made doesnt work as it should. 我所做的功能无法正常工作。 I can't see what is wrong, its not sorting the numbers properly. 我看不出有什么问题,它没有正确地对数字进行排序。

void linked_list::SortList()
{
   if(is_empty())
   {
      return;
   }
   for(node_t *it =head; it!=tail; it = it->next)
   {
      int valToIns = it->value;
      node_t *holePos = it;
      while(holePos->prev && valToIns < it->prev->value)
      {
         holePos->value = holePos->prev->value;
         holePos = holePos->prev;
      }
      holePos->value = valToIns;
   }
}

You're comparing with the wrong element, 您正在与错误的元素进行比较,

while(holePos->prev && valToIns < it->prev->value)

should be 应该

while(holePos->prev && valToIns < holePos->prev->value)

in order to compare valToIns with the value before the one holePos points to. 为了将valToIns与一个holePos指向之前的值进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM