Insertion sort on doubly linked list in swift
Swift program for Insertion sort on doubly linked list. Here problem description and other solutions.
import Foundation
// Swift 4 program for
// Perform insertion sort on doubly linked list
class LinkNode
{
var data: Int;
var next: LinkNode? ;
var prev: LinkNode? ;
init(_ data: Int)
{
self.data = data;
self.next = nil;
self.prev = nil;
}
}
class DoublyLinkedList
{
var head: LinkNode? ;
var tail: LinkNode? ;
init()
{
self.head = nil;
self.tail = nil;
}
// Insert new node at end position
func insert(_ value: Int)
{
// Create a node
let node: LinkNode? = LinkNode(value);
if (self.head == nil)
{
// Add first node
self.head = node;
self.tail = node;
return;
}
// Add node at last position
self.tail!.next = node;
node!.prev = self.tail;
self.tail = node;
}
// Display node element of doubly linked list
func display()
{
if (self.head == nil)
{
print("Empty Linked List");
}
else
{
print("\nLinked List Head to Tail ", terminator: ":");
// Get first node of linked list
var temp: LinkNode? = self.head;
// iterate linked list
while (temp != nil)
{
// Display node value
print("",temp!.data, terminator: " ");
// Visit to next node
temp = temp!.next;
}
print("\nLinked List Tail to Head ", terminator: ":");
// Get last node of linked list
temp = self.tail;
// iterate linked list
while (temp != nil)
{
// Display node value
print("",temp!.data, terminator: " ");
// Visit to prev node
temp = temp!.prev;
}
print();
}
}
// Swap value of given node
func swapData(_ first: LinkNode? , _ second : LinkNode? )
{
let value: Int = first!.data;
first!.data = second!.data;
second!.data = value;
}
// Sort elements using insertion sort
func insertionSort()
{
// Get first node
var front: LinkNode? = self.head;
var back: LinkNode? = nil;
while (front != nil)
{
// Get next node
back = front!.next;
// Update node value when consecutive nodes are not sort
while (back != nil && back!.prev != nil && back!.data < back!.prev!.data)
{
// Modified node data
self.swapData(back, back!.prev);
// Visit to previous node
back = back!.prev;
}
// Visit to next node
front = front!.next;
}
}
static func main(_ args: [String])
{
let dll: DoublyLinkedList? = 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", terminator: "");
dll!.display();
// Display all node
dll!.insertionSort();
print("\n After Sort", terminator: "");
dll!.display();
}
}
DoublyLinkedList.main([String]());
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