简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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