# Iterative Selection Sort For Linked List

### Problem Statement

In this problem we are given the head of a linked list denoting the whole linked list, we have to iteratively sort the linked list using selection sort. Suppose we have a linked list represented as - Then the sorted linked list is given as - Selection sort on the Linked list works in a similar way as it does on arrays but here instead of accessing the elements directly, we will be dealing with the links. Most of the Linked List problems are based on manipulation of the links.

### Approach & Algorithm

The idea is to Iterate over the given Linked list N times where N is the number of elements in the Linked list. In every iteration of the algorithm, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray of the Linked list.
Now we have to perform a similar swapping operation, which is done in Linked list in 2 ways -

• By swapping the data parts of the nodes.
• By swapping the complete nodes.

We will be using here the second way to swap the nodes by manipulating the links. While we do the swapping of the link parts of two nodes, four cases arise:

• When nodes are adjacent and the first node is the head node.
• Nodes can be adjacent and the first node isn’t the head node.
• Nodes might not be adjacent and the first node is the head node.
• Nodes might not be adjacent and the first node isn’t the head node.

### Iterative Selection Sort For Linked List

```#include
using namespace std;
struct Node {
int data;
Node* next;
};
Node* newNode(int val)
{
Node* temp = new Node;
temp->data = val;
temp->next = NULL;
return temp;
}
{
Node *x, *y, *z, *w, *s;
while (y->next) {
z = w = y->next;
while (w) {
if (y->data > w->data) {
if (y->next == w) {
y->next = w->next;
w->next = y;
s = y;
y = w;
w = s;
z = w;
w = w->next;
}
else {
y->next = w->next;
w->next = y;
x->next = w;
s = y;
y = w;
w = s;
z = w;
w = w->next;
}
}
else {
s = y->next;
y->next = w->next;
w->next = s;
z->next = y;
s = y;
y = w;
w = s;
z = w;
w = w->next;
}
else {
s = y->next;
y->next = w->next;
w->next = s;
z->next = y;
x->next = w;
s = y;
y = w;
w = s;
z = w;
w = w->next;
}
}
}
else {
z = w;
w = w->next;
}
}

x = y;
y = y->next;
}

}
{
}
}
int main()
{