# 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
{
var data: Int;
init(_ data: Int)
{
self.data = data;
self.next = nil;
self.prev = nil;
}
}
{
init()
{
self.tail = nil;
}
// Insert new node at end position
func insert(_ value: Int)
{
// Create a 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()
{
{
}
else
{
// Get first node of linked list
while (temp  != nil)
{
// Display node value
print("",temp!.data, terminator: " ");
// Visit to next node
temp = temp!.next;
}
// Get last node of linked list
temp = self.tail;
while (temp  != nil)
{
// Display node value
print("",temp!.data, terminator: " ");
// Visit to prev node
temp = temp!.prev;
}
print();
}
}
// Swap value of given node
{
let value: Int = first!.data;
first!.data = second!.data;
second!.data = value;
}
// Sort elements using insertion sort
func insertionSort()
{
// Get first node
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])
{
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();
}
}

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``````

## Comment

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.