简体   繁体   中英

Insertion Sort to Sort Nodes in a LinkedList

Im trying to use the insertion sort method in order to sort nodes from a LinkedList. I've adjusted the code so many times but I can't quite seem to get it, keep getting different types of results none which are sorted.

Heres the code:

Node* sort_list(Node* head)
{
    Node* node_ptr = NULL;
    for(Node* i = head->next; i->next != NULL; i = i->next){
            if (i->key < head->key) {
                node_ptr = i;
                head = head->next;
    }
    }
    return node_ptr;
}

This is a homework problem so instead of outright writing a code, I will first point out where you went wrong.

In an insertion sort like algorithm, obviously there needs to be some kind of swapping that needs to be done between elements that are out of place (that is need to be inserted). Hence start with thinking about how you can swap two elements of the array. Pay special attention to the cases when one is head or one is tail.

Your implemented code doesn't have any trace of pointer swaps so this is where you are wrong.

Next you must think about the cases when we need to sort. In this case, it is rather simple. If the current element and the next are in sorted order (assuming ascending order, current < next). Then nothing needs to be done but simply make the next one the current.

Then you can obviously infer that violation of this case is when you need to swap the elements. After the swap (with proper attention to where the pointers were and will be after sorting), repeat the process till you hit the null wall.

PS : This is a possible duplicate of another SO question.

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