I am trying to use Selection Sort to sort a Linked list. I can only manipulate the linked lists pointers and not change the keys. I think I have functional logic but, I just return the original unsorted sequence.
bool nodeSwap(Node* head){
Node* next = head->next;
if(next == NULL){ return head;}
head->next = next->next;
next->next = head;
head = next;
return next;
}
Node* sort_list(Node* head){
for(Node* n = head; n->next != NULL; n = n->next){
for(Node* n1 = head->next; n1 != NULL; n1 = n1->next){
if(n-> key > n1->key){
nodeSwap(n);
}
}
}
return head;
}
EDIT
Ok so I went through and added more and some logic which actually makes some sense this time and I have my function almost working... Only problem is it always skips sorting over whatever the first two elements are in the list and doesn't return after the sort. Any thoughts on why that might occur?
Node* sort_list(Node* head){
Node* curr;
Node* prev;
for(curr = head; curr->next != NULL; curr = curr->next){
if(curr == head){
head = curr->next;
curr->next = head->next;
head->next = curr;
prev = head;
}
else if(curr->key > curr->next->key){
head = curr->next;
curr->next = head->next;
head->next = curr;
prev = head;
} else if(curr -> next -> next != NULL){
prev->next = curr->next;
curr->next = prev->next->next;
prev->next->next = curr;
}else if(head != curr){
prev = prev->next;
}else{}
}
return head;
}