GeeksforGeeks App
Open App
Browser
Continue

# Javascript Program For Recursive Selection Sort For Singly Linked List – Swapping Node Links

Given a singly linked list containing n nodes. The problem is to sort the list using the recursive selection sort technique. The approach should be such that it involves swapping node links instead of swapping node data.

Examples:

```Input: 10 -> 12 -> 8 -> 4 -> 6
Output: 4 -> 6 -> 8 -> 10 -> 12 ```

In Selection Sort, we first find the minimum element, swap it with the beginning node and recur for the remaining list. Below is the recursive implementation of these steps for the linked list.

```recurSelectionSort(head)
Initialize beforeMin = NULL

while ptr->next != NULL
if min->data > ptr->next->data
min = ptr->next
beforeMin = ptr
ptr = ptr->next

prevY->next = currX

Initialize temp = currY->next
currY->next = currX->next
currX->next  = temp    ```

The swapNodes(head_ref, currX, currY, prevY) is based on the approach discussed here but it has been modified accordingly for the implementation of this post.

## Javascript

 ``

Output:

```Linked list before sorting:
10 12 8 4 6
4 6 8 10 12```

Time Complexity: O(n2)

Auxiliary Space: O(n)

Please refer complete article on Recursive selection sort for singly linked list | Swapping node links for more details!

My Personal Notes arrow_drop_up