Insertion sort on doubly linked list in scala
Scala program for Insertion sort on doubly linked list. Here more information.
// Scala program for
// Perform insertion sort on doubly linked list
class LinkNode(var data: Int,
var next: LinkNode,
var prev: LinkNode)
{
def this(data: Int)
{
this(data, null, null);
}
}
class DoublyLinkedList(var head: LinkNode,
var tail: LinkNode)
{
def this()
{
this(null, null);
}
// Insert new node at end position
def insert(value: Int): Unit = {
// Create a node
var node: LinkNode = 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
def display(): Unit = {
if (this.head == null)
{
println("Empty Linked List");
}
else
{
print("\nLinked List Head to Tail :");
// Get first node of linked list
var temp: LinkNode = this.head;
// iterate linked list
while (temp != null)
{
// Display node value
print(" " + temp.data);
// Visit to next node
temp = temp.next;
}
print("\nLinked List Tail to Head :");
// Get last node of linked list
temp = this.tail;
// iterate linked list
while (temp != null)
{
// Display node value
print(" " + temp.data);
// Visit to prev node
temp = temp.prev;
}
print("\n");
}
}
// Swap value of given node
def swapData(first: LinkNode, second: LinkNode): Unit = {
var value: Int = first.data;
first.data = second.data;
second.data = value;
}
// Sort elements using insertion sort
def insertionSort(): Unit = {
// Get first node
var front: LinkNode = this.head;
var back: LinkNode = 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
swapData(back, back.prev);
// Visit to previous node
back = back.prev;
}
// Visit to next node
front = front.next;
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
var dll: DoublyLinkedList = 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);
print("\n Before Sort");
dll.display();
// Display all node
dll.insertionSort();
print("\n After Sort");
dll.display();
}
}
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