Sorting A Singly Linked List
Sorting A Singly Linked List
#include<iostream>
#include<stdlib.h>
using namespace std;
/* List Structure */
typedef struct Node
{
int data;
struct Node *link;
}node;
/* Driver functions */
void print();
void swap(node *p1, node*p2);
void SelectionSort(node *head);
void insert(int data, int position);
/* Main method */
int main()
{
insert(4,1); // Insert Element at first position LINKED-LIST = / 4 /
insert(2,2); // Insert Element at second position LINKED-LIST = / 4 2 /
insert(3,3); // Insert Element at third position LINKED-LIST = / 4 2 3 /
insert(1,4); // Insert Element at fourth position LINKED-LIST = / 4 2 3 1/
insert(0,5); // Insert Element at fifth position LINKED-LIST = / 4 2 3 1 0/
return 0;
}
/* To sort the linked list */
void SelectionSort(node *head)
{
node *start = head;
node *traverse;
node *min;
while(start->link)
{
min = start;
traverse = start->link;
while(traverse)
{
/* Find minimum element from array */
if( min->data > traverse->data )
{
min = traverse;
}
traverse = traverse->link;
}
swap(start,min); // Put minimum element on starting location
start = start->link;
}
}
while(p)
{
printf(" %d",p->data);
p = p->link;
}
printf(" \n\n");
}