Insertion sort linked list c++

梦想与她 提交于 2019-12-12 00:09:41

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/16426104/insertion-sort-linked-list-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!