Bubble sort on linked list in swift

Swift program for Bubble sort on linked list. Here more solutions.
import Foundation
// Swift program for
// Bubble Sort For Linked List
class Node
{
var data : Int;
var next : Node?;
init(_ data : Int)
{
self.data = data;
self.next = nil;
}
}
class LinkedList
{
var head : Node?;
// Class constructors
init()
{
self.head = nil;
}
// Add node at the beginning of linked list
func insert(_ value : Int)
{
// Create a new node
let node : Node? = Node(value);
// Add node at front
node!.next = self.head;
// Make new head
self.head = node;
}
// Display all elements
func display()
{
if (self.head != nil)
{
var temp : Node? = self.head;
while (temp != nil)
{
// Display node value
print(temp!.data,terminator: " ");
// Visit to next node
temp = temp!.next;
}
}
else
{
print("Empty Linked list");
}
}
// Perform bubble sort in single linked list
func bubbleSort()
{
if (self.head != nil)
{
var current : Node? = nil;
var status : Bool = false;
repeat
{
// Start with first node
current = self.head;
// Reset working status
status = false;
while (current != nil && current!.next != nil)
{
if (current!.data > current!.next!.data)
{
// Swap node values
current!.data = current!.data + current!.next!.data;
current!.next!.data = current!.data - current!.next!.data;
current!.data = current!.data - current!.next!.data;
// When node value change
status = true;
}
// Visit to next node
current = current!.next;
}
} while (status);
}
else
{
print("Empty Linked list");
}
}
static func main()
{
let task : LinkedList = LinkedList();
// Insert element of linked list
task.insert(15);
task.insert(5);
task.insert(42);
task.insert(9);
task.insert(50);
task.insert(7);
print(" Before sort : ",terminator: "");
// Display all node
task.display();
task.bubbleSort();
print("\n After sort : ",terminator: "");
task.display();
}
}
LinkedList.main();
Output
Before sort : 7 50 9 42 5 15
After sort : 5 7 9 15 42 50
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