Insertion sort on doubly linked list in php
Php program for Insertion sort on doubly linked list. Here problem description and explanation.
<?php
// Php program for
// Perform insertion sort on doubly linked list
class LinkNode
{
public $data;
public $next;
public $prev;
public function __construct($data)
{
$this->data = $data;
$this->next = NULL;
$this->prev = NULL;
}
}
class DoublyLinkedList
{
public $head;
public $tail;
public function __construct()
{
$this->head = NULL;
$this->tail = NULL;
}
// Insert new node at end position
public function insert($value)
{
// Create a node
$node = new LinkNode($value);
if ($this->head == NULL)
{
// Add first node
$this->head = $node;
$this->tail = $node;
return;
}
// Add node at last position
$this->tail->next = $node;
$node->prev = $this->tail;
$this->tail = $node;
}
// Display node element of doubly linked list
public function display()
{
if ($this->head == NULL)
{
printf("Empty Linked List\n");
}
else
{
printf("\nLinked List Head to Tail : ");
// Get first node of linked list
$temp = $this->head;
// iterate linked list
while ($temp != NULL)
{
// Display node value
printf(" %d ",$temp->data);
// Visit to next node
$temp = $temp->next;
}
printf("\nLinked List Tail to Head : ");
// Get last node of linked list
$temp = $this->tail;
// iterate linked list
while ($temp != NULL)
{
// Display node value
printf(" %d ",$temp->data);
// Visit to prev node
$temp = $temp->prev;
}
printf("\n");
}
}
// Swap value of given node
public function swapData($first, $second)
{
$value = $first->data;
$first->data = $second->data;
$second->data = $value;
}
// Sort elements using insertion sort
public function insertionSort()
{
// Get first node
$front = $this->head;
$back = NULL;
while ($front != NULL)
{
// Get next node
$back = $front->next;
// Update node value when consecutive nodes are not sort
while ($back != NULL &&
$back->prev != NULL &&
$back->data < $back->prev->data)
{
// Modified node data
$this->swapData($back, $back->prev);
// Visit to previous node
$back = $back->prev;
}
// Visit to next node
$front = $front->next;
}
}
public static
function main($args)
{
$dll = new DoublyLinkedList();
//Insert element of linked list
$dll->insert(25);
$dll->insert(2);
$dll->insert(6);
$dll->insert(14);
$dll->insert(12);
$dll->insert(9);
$dll->insert(16);
$dll->insert(3);
printf("\n Before Sort");
$dll->display();
// Display all node
$dll->insertionSort();
printf("\n After Sort");
$dll->display();
}
}
DoublyLinkedList::main(array());
Output
Before Sort
Linked List Head to Tail : 25 2 6 14 12 9 16 3
Linked List Tail to Head : 3 16 9 12 14 6 2 25
After Sort
Linked List Head to Tail : 2 3 6 9 12 14 16 25
Linked List Tail to Head : 25 16 14 12 9 6 3 2
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment