Open in App
Not now

Sorting given character Array using Linked List

• Difficulty Level : Hard
• Last Updated : 24 Jan, 2023

Given an array arr[] containing N lowercase English alphabets, the task is to sort this array arr[] using a linked list.

Examples:

Input: arr[] = [‘b’, ‘b’, ‘c’, ‘c’, ‘d’, ‘e’, ‘f’, ‘b’, ‘b’, ‘a’, ‘a’]
Output: a->a->b->b->b->b->c->c->d->e->f->NULL

Input: arr[] = [‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’]
Output: e->e->e->e->f->g->g->k->k->o->r->s->s->NULL

Approach: To solve this problem, first create the linked list from the character array. After the linked list has been formed, sort it using bubble sort.

Below is the implementation of the above approach:

C++

 `#include ` `using` `namespace` `std;`   `// Structure for a node` `struct` `Node {` `    ``int` `data;` `    ``Node* next;` `} Node;`   `// Function to swap the nodes` `struct` `Node* swap(``struct` `Node* ptr1, ``struct` `Node* ptr2)` `{` `    ``struct` `Node* tmp = ptr2->next;` `    ``ptr2->next = ptr1;` `    ``ptr1->next = tmp;` `    ``return` `ptr2;` `}`   `// Function to sort the list` `void` `bubbleSort(``struct` `Node** head, ``int` `count)` `{` `    ``struct` `Node** h;` `    ``int` `i, j, swapped;`   `    ``for` `(i = 0; i <= count; i++) {`   `        ``h = head;` `        ``swapped = 0;`   `        ``for` `(j = 0; j < count - i - 1; j++) {`   `            ``struct` `Node* p1 = *h;` `            ``struct` `Node* p2 = p1->next;`   `            ``if` `(p1->data > p2->data) {`   `                ``// Update the link after swapping` `                ``*h = swap(p1, p2);` `                ``swapped = 1;` `            ``}`   `            ``h = &(*h)->next;` `        ``}`   `        ``// Break if the loop ended` `        ``// without any swap` `        ``if` `(swapped == 0)` `            ``break``;` `    ``}` `}`   `// Function to print the list` `void` `printList(``struct` `Node* n)` `{` `    ``while` `(n != NULL) {` `        ``cout << ``char``(n->data) << ``" -> "``;` `        ``n = n->next;` `    ``}` `    ``cout << ``"NULL"` `<< endl;` `}`   `// Function to insert a struct Node` `// at the end of a linked list` `void` `insert(``struct` `Node** head, ``int` `data)` `{` `    ``struct` `Node* ptr = ``new` `struct` `Node();`   `    ``ptr->data = data;` `    ``ptr->next = NULL;` `    ``if` `(*head == NULL) {` `        ``*head = ptr;` `    ``}` `    ``else` `{` `        ``struct` `Node* ptr1 = *head;` `        ``while` `(ptr1->next != NULL) {` `            ``ptr1 = ptr1->next;` `        ``}` `        ``ptr1->next = ptr;` `    ``}` `}`   `// Driver Code` `int` `main()` `{` `    ``int` `arr[] = { ``'b'``, ``'b'``, ``'c'``, ``'c'``, ``'d'``, ``'e'``,` `                  ``'f'``, ``'b'``, ``'b'``, ``'a'``, ``'a'` `};` `    ``int` `list_size, i;`   `    ``// start with empty linked list` `    ``struct` `Node* start = NULL;` `    ``list_size = ``sizeof``(arr) / ``sizeof``(arr[0]);`   `    ``// Create linked list from the array arr[]` `    ``for` `(i = 0; i < list_size; i++)` `        ``insert(&start, arr[i]);`   `    ``// sort the linked list` `    ``bubbleSort(&start, list_size);`   `    ``// Print list after sorting` `    ``printList(start);`   `    ``return` `0;` `}`

Java

 `// Java code for the above approach`   `import` `java.io.*;` `import` `java.util.*;`   `// Defined class for adding nodes` `class` `Node {` `  ``int` `data;` `  ``Node link;`   `  ``public` `Node(``int` `data, Node link)` `  ``{` `    ``this``.data = data;` `    ``this``.link = link;` `  ``}`   `  ``public` `String toString()` `  ``{` `    ``return` `String.valueOf((``char``) ``this``.data);` `  ``}` `}`   `// Defined class for linked list` `class` `LinearList {` `  ``Node start;` `  ``int` `count;`   `  ``public` `LinearList(Node start, ``int` `count)` `  ``{` `    ``this``.start = start;` `    ``this``.count = count;` `  ``}`   `  ``// Beginning Node` `  ``void` `begNode(``int` `value)` `  ``{` `    ``Node node = ``new` `Node(value, ``this``.start);` `    ``this``.start = node;` `    ``this``.count++;` `  ``}`   `  ``// Traversing the Linked list` `  ``void` `printList()` `  ``{` `    ``Node ptr = ``this``.start;` `    ``while` `(ptr != ``null``) {` `      ``System.out.print(ptr + ``" -> "``);` `      ``ptr = ptr.link;` `    ``}` `    ``System.out.println(``"NULL"``);` `  ``}`   `  ``void` `bubbleSort()` `  ``{` `    ``// Loop for sorting the Linked List` `    ``for` `(``int` `i = ``0``; i < ``this``.count - ``1``; i++) {` `      ``Node curr = ``this``.start;` `      ``Node nxt = curr.link;` `      ``Node prev = ``null``;` `      ``// Comparisons in each passes` `      ``while` `(nxt != ``null``) {` `        ``if` `(curr.data > nxt.data) {` `          ``if` `(prev == ``null``) {` `            ``prev = curr.link;` `            ``nxt = nxt.link;` `            ``prev.link = curr;` `            ``curr.link = nxt;` `            ``this``.start = prev;` `          ``}` `          ``else` `{` `            ``Node temp = nxt;` `            ``nxt = nxt.link;` `            ``prev.link = curr.link;` `            ``prev = temp;` `            ``temp.link = curr;` `            ``curr.link = nxt;` `          ``}` `        ``}` `        ``else` `{` `          ``prev = curr;` `          ``curr = nxt;` `          ``nxt = nxt.link;` `        ``}` `      ``}` `    ``}` `  ``}` `}`   `class` `GFG {` `  ``public` `static` `void` `main(String[] args)` `  ``{`   `    ``// Created empty linked list over here` `    ``LinearList ll = ``new` `LinearList(``null``, ``0``);` `    ``char``[] array1 = { ``'b'``, ``'b'``, ``'c'``, ``'c'``, ``'d'``, ``'e'``,` `                     ``'f'``, ``'b'``, ``'b'``, ``'a'``, ``'a'` `};`   `    ``// Adding nodes in the linked list from the array1` `    ``// list` `    ``for` `(``int` `cnt = ``0``; cnt < array1.length; cnt++)` `      ``ll.begNode(array1[cnt]);`   `    ``ll.bubbleSort();` `    ``ll.printList();` `  ``}` `}`   `// This code is contributed by lokesh.`

Python3

 `# Defined class for adding nodes` `class` `Node:` `    ``def` `__init__(``self``, data``=``None``, link``=``None``):` `        ``self``.data ``=` `data` `        ``self``.link ``=` `link`   `    ``def` `__str__(``self``):` `        ``return` `str``(``self``.data)`     `# Defined class for linked list` `class` `LinearList:` `    ``def` `__init__(``self``, start``=``None``, count``=``0``):` `        ``self``.start ``=` `start` `        ``# Counting number of nodes in linked List` `        ``self``.count ``=` `count`   `    ``# Beginning Node` `    ``def` `beg_node(``self``, value``=``None``):` `        ``node ``=` `Node(value)` `        ``node.link ``=` `self``.start` `        ``self``.start ``=` `node` `        ``self``.count ``=` `self``.count ``+` `1`   `    ``# Traversing the Linked list` `    ``def` `print_list(``self``):` `        ``ptr ``=` `self``.start` `        ``while` `ptr:` `            ``print``(ptr, end``=``"->"``)` `            ``ptr ``=` `ptr.link` `        ``print``(``'NULL'``, end``=``"")` `        ``print``()`   `    ``def` `bubble_sort(``self``):` `        ``# Loop for sorting the Linked List` `        ``for` `i ``in` `range``(``self``.count ``-` `1``):` `            ``curr ``=` `self``.start` `            ``nxt ``=` `curr.link` `            ``prev ``=` `None` `            ``# Comparisons in each passes` `            ``while` `nxt:` `                ``if` `curr.data > nxt.data:` `                    ``if` `prev ``=``=` `None``:` `                        ``prev ``=` `curr.link` `                        ``nxt ``=` `nxt.link` `                        ``prev.link ``=` `curr` `                        ``curr.link ``=` `nxt` `                        ``self``.start ``=` `prev` `                    ``else``:` `                        ``temp ``=` `nxt` `                        ``nxt ``=` `nxt.link` `                        ``prev.link ``=` `curr.link` `                        ``prev ``=` `temp` `                        ``temp.link ``=` `curr` `                        ``curr.link ``=` `nxt` `                ``else``:` `                    ``prev ``=` `curr` `                    ``curr ``=` `nxt` `                    ``nxt ``=` `nxt.link` `            ``i ``=` `i ``+` `1`     `# Created empty linked list over here` `ll ``=` `LinearList()` `array1 ``=` `[``'b'``, ``'b'``, ``'c'``, ``'c'``, ``'d'``, ``'e'``, ``'f'``, ``'b'``, ``'b'``, ``'a'``, ``'a'``]`   `# Adding nodes in the linked list from the Array1 list` `for` `cnt ``in` `range``(``len``(array1)):` `    ``ll.beg_node(array1[cnt])`   `ll.bubble_sort()` `print``(``"Sorted Linked List: "``, end``=``"")` `ll.print_list()`

C#

 `// C# code for the above approach` `using` `System;`   `// Defined class for adding nodes` `class` `Node {` `  ``public` `int` `data;` `  ``public` `Node link;`   `  ``public` `Node(``int` `data, Node link)` `  ``{` `    ``this``.data = data;` `    ``this``.link = link;` `  ``}`   `  ``public` `override` `string` `ToString()` `  ``{` `    ``return` `((``char``)``this``.data).ToString();` `  ``}` `}`   `// Defined class for linked list` `class` `LinearList {` `  ``public` `Node start;` `  ``public` `int` `count;`   `  ``public` `LinearList(Node start, ``int` `count)` `  ``{` `    ``this``.start = start;` `    ``this``.count = count;` `  ``}`   `  ``// Beginning Node` `  ``public` `void` `begNode(``int` `value)` `  ``{` `    ``Node node = ``new` `Node(value, ``this``.start);` `    ``this``.start = node;` `    ``this``.count++;` `  ``}`   `  ``// Traversing the Linked list` `  ``public` `void` `printList()` `  ``{` `    ``Node ptr = ``this``.start;` `    ``while` `(ptr != ``null``) {` `      ``Console.Write(ptr + ``" -> "``);` `      ``ptr = ptr.link;` `    ``}` `    ``Console.WriteLine(``"NULL"``);` `  ``}`   `  ``public` `void` `bubbleSort()` `  ``{` `    ``// Loop for sorting the Linked List` `    ``for` `(``int` `i = 0; i < ``this``.count - 1; i++) {` `      ``Node curr = ``this``.start;` `      ``Node nxt = curr.link;` `      ``Node prev = ``null``;` `      ``// Comparisons in each passes` `      ``while` `(nxt != ``null``) {` `        ``if` `(curr.data > nxt.data) {` `          ``if` `(prev == ``null``) {` `            ``prev = curr.link;` `            ``nxt = nxt.link;` `            ``prev.link = curr;` `            ``curr.link = nxt;` `            ``this``.start = prev;` `          ``}` `          ``else` `{` `            ``Node temp = nxt;` `            ``nxt = nxt.link;` `            ``prev.link = curr.link;` `            ``prev = temp;` `            ``temp.link = curr;` `            ``curr.link = nxt;` `          ``}` `        ``}` `        ``else` `{` `          ``prev = curr;` `          ``curr = nxt;` `          ``nxt = nxt.link;` `        ``}` `      ``}` `    ``}` `  ``}` `}`   `public` `class` `GFG {` `  ``static` `public` `void` `Main()` `  ``{`   `    ``// Created empty linked list over here` `    ``LinearList ll = ``new` `LinearList(``null``, 0);` `    ``char``[] array1 = { ``'b'``, ``'b'``, ``'c'``, ``'c'``, ``'d'``, ``'e'``,` `                     ``'f'``, ``'b'``, ``'b'``, ``'a'``, ``'a'` `};`   `    ``// Adding nodes in the linked list from the array1` `    ``// list` `    ``for` `(``int` `cnt = 0; cnt < array1.Length; cnt++)` `      ``ll.begNode(array1[cnt]);`   `    ``ll.bubbleSort();` `    ``ll.printList();` `  ``}` `}`   `// This code is contributed by akashish__`

Javascript

 `// Defined class for adding nodes` `class Node {` `    ``constructor(data = ``null``, link = ``null``) {` `        ``this``.data = data;` `        ``this``.link = link;` `    ``}`   `    ``toString() {` `        ``return` `this``.data;` `    ``}` `}`   `// Defined class for linked list` `class LinearList {` `    ``constructor(start = ``null``, count = 0) {` `        ``this``.start = start;` `        ``// Counting number of nodes in linked List` `        ``this``.count = count;` `    ``}`   `    ``// Beginning Node` `    ``begNode(value = ``null``) {` `        ``const node = ``new` `Node(value);` `        ``node.link = ``this``.start;` `        ``this``.start = node;` `        ``this``.count = ``this``.count + 1;` `    ``}`   `    ``// Traversing the Linked list` `    ``printList() {` `        ``let ptr = ``this``.start;` `        ``let ans = ``""``;` `        ``while` `(ptr) ` `        ``{` `        `  `            ``// console.log(ptr.data, end = "->");` `            ``ans+=ptr.data+``"->"``;` `            ``ptr = ptr.link;` `        ``}` `        ``console.log(ans,``"NULL"``);` `    ``}`   `    ``bubbleSort()` `    ``{` `    `  `        ``// Loop for sorting the Linked List` `        ``for` `(let i = 0; i < ``this``.count - 1; i++) {` `            ``let curr = ``this``.start;` `            ``let nxt = curr.link;` `            ``let prev = ``null``;` `            `  `            ``// Comparisons in each passes` `            ``while` `(nxt) {` `                ``if` `(curr.data > nxt.data) {` `                    ``if` `(!prev) {` `                        ``prev = curr.link;` `                        ``nxt = nxt.link;` `                        ``prev.link = curr;` `                        ``curr.link = nxt;` `                        ``this``.start = prev;` `                    ``} ``else` `{` `                        ``const temp = nxt;` `                        ``nxt = nxt.link;` `                        ``prev.link = curr.link;` `                        ``prev = temp;` `                        ``temp.link = curr;` `                        ``curr.link = nxt;` `                    ``}` `                ``} ``else` `{` `                    ``prev = curr;` `                    ``curr = nxt;` `                    ``nxt = nxt.link;` `                ``}` `            ``}` `        ``}` `    ``}` `}`   `// Created empty linked list over here` `const ll = ``new` `LinearList();` `const array1 = [``"b"``, ``"b"``, ``"c"``, ``"c"``, ``"d"``, ``"e"``, ``"f"``, ``"b"``, ``"b"``, ``"a"``, ``"a"``];`   `// Adding nodes in the linked list from the Array1 list` `for` `(let cnt = 0; cnt < array1.length; cnt++) {` `    ``ll.begNode(array1[cnt]);` `}`   `ll.bubbleSort();` `console.log(``"Sorted Linked List: "``, end = ``""``);` `ll.printList();`   `// This code is contributed by akashish__`

Output

`a -> a -> b -> b -> b -> b -> c -> c -> d -> e -> f -> NULL`

Time Complexity: O(N2)

My Personal Notes arrow_drop_up
Related Articles