Nora
Nora

Reputation: 165

Sorting a linked list in c++

I'm getting mad with infinite loop, what do you think is suitable solution?

void sorting () {
  node * temphead = head;
  node * tempnode = NULL;

  for (int i=0; i<count; i++) {
    for (int j=0; j<count-i; j++) {
      if (temphead->data > temphead->next->data) {
        tempnode = temphead;
        temphead = temphead->next;
        temphead->next = tempnode;
      }

      temphead=temphead->next;
      count++;
    }
  }
}

I tried to increment count and use many conditions with while- before and after the for loop with no result

Upvotes: 2

Views: 11509

Answers (2)

sircodesalot
sircodesalot

Reputation: 11439

An easier way to slide through a linked list is like this:

for (node *current = head; current != nullptr; current = current->next) {
    // This will run through all of the nodes until we reach the end.
}

And to slide to the second to last item (ensuring that node->next exists) looks like this:

for (node *current = head; current->next != nullptr; current = current->next) {
    // Go through all of the nodes that have a 'next' node.
}

If you want to count how many items are in a linked list, you do something like this:

int count = 0;
for (node *current = head; current != nullptr; current = current->next) {
    count = count + 1;
}

So a selection type sort like you have above would look like this:

for (node *index = head; index->next != nullptr; index = index->next) {
  for (node *selection = index->next; selection != nullptr; selection = selection->next) {
    if (index->data > selection->data) {
      swap(index->data, selection->data);
    }
  }
}

Although sorting linked lists is generally not the best way to go (unless you're performing a merge).

Upvotes: 5

Kaushik Sivakumar
Kaushik Sivakumar

Reputation: 205

the problem is you are looping till count and you are incrementing count in every run of the loop//remove line count++ to avoid remove infinite loop

Upvotes: 2

Related Questions