Question

In: Computer Science

how do you write a bubble sort function in python that sorts a linked list and...

how do you write a bubble sort function in python that sorts a linked list and if any duplicate are placed bext ti each other?

Solutions

Expert Solution

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 11:50:03 2019

@author: pavan
"""

# -*- coding: utf-8 -*-
"""
Created on Wed Sep 18 11:24:11 2019

@author: pavan
"""
#creating a node which contains data and referrence of next node
class Node:
    def __init__(self, data):
        self.item = data
        self.next = None
#creating a linked list which contains following functions
#printing linked list
#inserting new node to the linked list
# sort function gives us the sorted linked list using bubble sort     
class linkedlist:
    def __init__(self):
        self.root = None
    def printing_list(self):#checks the empty condition for linked list
      if self.root is None:
          print("List is empty")
          return
      else:
         n = self.root
         while n is not None:
            print(n.item , " ")#printing data inside every node sequencially
            n = n.next
    def insertingnode(self, data):
        new_node = Node(data)
        if self.root is None:
            self.root = new_node
            return
        n = self.root
        while n.next is not None:
            n= n.next
        n.next = new_node;#inserting a new node to the linked list at the end
    def sort(self):#this is the actual bubble sort code
        if self.root is None:
          print("List has no element")
          return
        else:
           n = self.root
           while n is not None:
               k=self.root
               while k.next is not None:
                     if(k.item>k.next.item):#checking adjacent node's data#swap if those are not in ascending order
                         t=k.item
                         k.item=k.next.item
                         k.next.item=t
                     k=k.next
               n=n.next
             
            
new_linkedlist = linkedlist()#creating an object to the linkedlist class
#inserting nodes to the linked list
new_linkedlist.insertingnode(5)
new_linkedlist.insertingnode(15)
new_linkedlist.insertingnode(10)
new_linkedlist.insertingnode(15)
new_linkedlist.insertingnode(5)

#sorting and printing linked list
new_linkedlist.sort()
new_linkedlist.printing_list()


output for the above code

      


Related Solutions

I need to write a method that sorts a provided Linked list with bubble sort and...
I need to write a method that sorts a provided Linked list with bubble sort and using ONLY Java List Iterator Methods (Link Below) https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html     public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {     // first line to start you off     ListIterator<E> iit = c.listIterator(), jit;     /**** Test code: do not modify *****/     List cc = new LinkedList(c);     Collections.sort(c);     ListIterator it1 = c.listIterator(), it2 = cc.listIterator(); while (it1.hasNext()) { if (!it1.next().equals(it2.next()))         throw new Exception("List not sorted");...
Write a MIPS program using the Bubble Sort algorithm, that sorts an input list of integers...
Write a MIPS program using the Bubble Sort algorithm, that sorts an input list of integers by repeatedly calling a “swap” subroutine. The original unsorted list of integers should be received from the keyboard input. Your program should first prompt the user “Please input an integer for the number of elements:”. After the user enters a number and return, your program outputs message “Now input each element and then a return:”. For example, if the user enters 5 as the...
Python 3 Function which takes the head Node of a linked list and sorts the list...
Python 3 Function which takes the head Node of a linked list and sorts the list into non-descending order. PARAM: head_node The head of the linked list RETURNS: The node at the head of the sorted linked list. ''' def sort(head_node): #Code goes here ''' Test code goes here '' ' if __name__ == '__main__':
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show...
1.)recursive merge sort on a list.(Python) 2.)recursive bubble sort using a list without enumerate() function.(python) Show Base case, and recursive case.
How do you write an append function for a linked list that is a that has...
How do you write an append function for a linked list that is a that has a O(1) Big O notation in Python? The one given in class is O(n). He recommended using a variable to track the end the list. This is the code I have written so far. I don't think I'm properly defining the tail in the add possibly class Node: def __init__(self, init_data): self.data = init_data self.next = None def get_data(self): return self.data def get_next(self): return...
Write a Y86 program in C language that sorts an array of data using Bubble Sort....
Write a Y86 program in C language that sorts an array of data using Bubble Sort. Allow the user to input up to 10 numbers from the keyboard. Sort the array in place (i.e., no need to allocate additional memory for the sorted array). Your program should be a complete one
Write a program to implement and analyzing the Bubble Sort. a. Write a C++ function for...
Write a program to implement and analyzing the Bubble Sort. a. Write a C++ function for Bubble Sort b. Use a dynamic array of integers in a variable size of n. c. Display the following information: 1) Total counts of comparisons 2) Total counts of shifts / moves / swaps, whichever applies d. Write a main() function to test a best, and an average cases in terms of time efficiency i. Fill out the array with random numbers for an...
For this assignment, find out how to do a bubble sort, selection sort, or insertion sort...
For this assignment, find out how to do a bubble sort, selection sort, or insertion sort in Java. You have the option to choose but you must label (with comments) the algorithm you choose to implement. Convert that algorithm to a generic algorithm and constraint it to only using numerics. Your method should accept an array as a parameter and sort the content of the array. If you wish, you can throw an exception if the contents of the array...
Please use C++, linked list and Bubble Sort to slove this problem. #include <iostream> #include <time.h>...
Please use C++, linked list and Bubble Sort to slove this problem. #include <iostream> #include <time.h> using namespace std; struct ListNode { int data; ListNode *next; ListNode(int x) : data(x), next(nullptr) {} }; class LinkedList { private: ListNode *head = nullptr; public: void addNode(int x) { ListNode *p = new ListNode(x); if (head == nullptr) head = p; else { ListNode *q = head; while (q->next != nullptr) q = q->next; q->next = p; } } void display() { ListNode...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list instead of arrays. You can use any kind of a linked structure, such as single, double, circular lists, stacks and/or queues. You can populate your list from an explicitly defined array in your program. HINT: You will not be using low, middle and high anymore. For finding the middle point, traverse through the linked list while keeping count of the number of nodes. Break...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT