In an online event, I have to complete a partially finished code.
They use linklist data structure to store each element.The time complexity is O(n*n)
And in the outer (for) loop, the iteration is completed when node->next!= NULL (i.e. only n-1 checks).
Inner (for) loop, there are n checks until (ptr becomes NULL)
say, there are 5 elements.
And,
Elements in given order
5 ->3 ->1 ->2 ->4 ->NULL
Sort Cycles:
1 ->3 ->5 ->2 ->4 ->NULL
1 ->2 ->5 ->3 ->4 ->NULL
1 ->2 ->3 ->5 ->4 ->NULL
1 ->2 ->3 ->4 ->5 ->NULL
Elements in sorted order
1 ->2 ->3 ->4 ->5 ->NULL
Which sorting algorithm is used here?
This is an instance of selection sort. Notice that after iteration i, the first i elements of the list are now in sorted order, and that the element that was moved into the ith position is swapped with the element that used to be there. For example, here’s the change from the first iteration to the second:
Notice that 1 (the smallest element) has been swapped to the front, but the rest of the elements are in the same order. Similarly, between the second and third iterations, you see this:
Here, 2, the second-smallest element, is swapped to the second position, but the rest of the elements are in the same order.
I’m not sure why they opted to use selection sort here. There are much better ways to sort a linked list.
Hope this helps!