Think about how Sorting Sort works: it βsplitsβ (theoretically) the list into three groups: a sorted subset (which may be empty), the current element, and an unsorted subset (which may be empty). Everything until the current item is sorted. Everything after the current item may or may not be sorted. The algorithm checks the current element by comparing it with the next element. Remember that the first item after the current item belongs to an unsorted subset.
Suppose you are sorting integers in ascending order (so given "3,1,5,2,4", you want to get "1,2,3,4,5"). You set your current item to the first item in the list. Now you start sorting:
If the next item is larger than the current, you do not need to sort this item. Just make it the "current item" and continue.
If the next element is smaller than the current element, then you have some work to do. First, save the next item somewhere β say in a pointer called temp β and then βremoveβ the next item from the list by doing the current-> next = current-> next-> next. Now you need to find the right place for the deleted item. You can do this in two ways:
- Or start at the beginning of the list, going forward until you find the right position. As soon as you do this, you insert the element there and continue to sort the insert. This is the easiest solution if you have a singly linked list.
- You go back until you find the right place for the item. As soon as you do this, you insert the element there and continue to sort the insert. This is a bit more, but may work well if you have a double-linked list.
You continue this process until you reach the end of the list. Once you achieve this, you know that you have finished sorting the insert, and the list is in the correct sort order.
Hope this helps.
source share