1

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?

Muthu Ganapathy Nathan
  • 3,199
  • 16
  • 47
  • 77

2 Answers2

5

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:

5 ->3 ->1 ->2 ->4 ->NULL
1 ->3 ->5 ->2 ->4 ->NULL

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:

1 ->3 ->5 ->2 ->4 ->NULL
1 ->2 ->5 ->3 ->4 ->NULL

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!

Community
  • 1
  • 1
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

It looks like selection sort, firstly the smallest of all and then the smallest of the rest and put the result after the first.

manuzhang
  • 2,995
  • 4
  • 36
  • 67