Bubble sort on linked list in golang

Go program for Bubble sort on linked list. Here more solutions.
package main
import "strconv"
import "fmt"
// go lang program for
// Bubble Sort For Linked List
type Node struct {
data int
next* Node
}
func getNode(data int) * Node{
// return new Node
return &Node{data, nil}
}
type LinkedList struct {
head* Node
}
func getLinkedList() * LinkedList{
// return new LinkedList
return &LinkedList{nil}
}
// Add node at the beginning of linked list
func (this *LinkedList) insert( value int) {
// Create a new node
var node* Node = getNode(value);
// Add node at front
node.next = this.head;
// Make new head
this.head = node;
}
// Display all elements
func (this *LinkedList) display() {
if (this.head != nil) {
var temp* Node = this.head;
for(temp != nil) {
// Display node value
fmt.Print(" " + strconv.Itoa(temp.data));
// Visit to next node
temp = temp.next;
}
} else {
fmt.Println("Empty Linked list");
}
}
// Perform bubble sort in single linked list
func (this *LinkedList) bubbleSort() {
if (this.head != nil) {
var current* Node = nil;
var status bool = false;
for {
// Start with first node
current = this.head;
// Reset working status
status = false;
for(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;
}
if ! (status){
break;
}
}
} else {
fmt.Println("Empty Linked list");
}
}
func main() {
var task* LinkedList = getLinkedList();
// Insert element of linked list
task.insert(15);
task.insert(5);
task.insert(42);
task.insert(9);
task.insert(50);
task.insert(7);
fmt.Print(" Before sort : ");
// Display all node
task.display();
task.bubbleSort();
fmt.Print("\n After sort : ");
task.display();
}
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