Question

In: Computer Science

How would I make a bubble sort and an optimized bubble sort with the code given?...

How would I make a bubble sort and an optimized bubble sort with the code given? I also need to implement a timer into each sort and display runtime with the sorts.

NODE.H
_______________________________________________________________________________________________________

/* node.h */
/*

two classes 1: node.h 2. singlylinkedlist.h

nod1 (value + pointer) ---> node2 ---> node3 ---> |||| <--- node.h
^
| singlylinkedlist
----------------*node head;

*/

#ifndef NODE_H
#define NODE_H

#include <iostream>
using namespace std;

class Node {
   friend class singlyLinkedList;
public:
   Node();
   Node (int value);
   ~Node();
   int displayValue();
private:
   int value;
   Node* next;
};

#endif

SINGLYLINKEDLIST.H
_______________________________________________________________________________________________________

/* singlylinkedlist.h */

#ifndef SINGLY_LINKED_LIST_H
#define SINGLY_LINKED_LIST_H

#include <iostream>
using namespace std;

#include "node.h"

class singlyLinkedList
{
public:
   singlyLinkedList();
   ~singlyLinkedList();
   void addFront(Node* newNode);
   void displaySinglyLinkedList();
   void bubbleSort();
   void optimizedBubbleSort();
private:
   Node *head;
};

#endif

NODE.CPP
_______________________________________________________________________________________________________

/* node.cpp */

#include <iostream>
using namespace std;

#include "node.h"

Node::Node()
{
   value = 0;
   next = NULL;
}

Node::Node(int v)
{
   value = v;
   next = NULL;
}

Node::~Node()
{
}

int Node::displayValue()
{
   return value;
}

SINGLYLINKEDLIST.CPP
_______________________________________________________________________________________________________

/* singlylinkedlist */

#include <iostream>
using namespace std;

#include "singlylinkedlist.h"

singlyLinkedList::singlyLinkedList()
{
   head = NULL;
}

singlyLinkedList::~singlyLinkedList()
{
}

void singlyLinkedList::addFront(Node *newNode)
{
   if (head == NULL)
       head = newNode;
   else
   {
       // Add code here!
       /* node1-->||| (before) what is after node2 --> node1 -->||| */

       newNode->next = head;
       head = newNode;
   };
}

void singlyLinkedList::displaySinglyLinkedList()
{
   Node *tempHead;

   tempHead = head;

   while (tempHead != NULL)
   {
       cout << tempHead->value << " ";
       tempHead = tempHead->next;
   }
   cout << endl;
}

void singlyLinkedList:: bubbleSort()
{
   // Your Code Starts Here!
   // Please display the runtime for this task before exit
   // start clock
   // ....
   // stop the clock
   // display the (stop-clock - start-clock
}

void singlyLinkedList:: optimizedBubbleSort()
{
   // Your Code Starts Here!
   // Please display the runtime for this task before exit
   // start clock
   // ....
   // stop the clock
   // display the (stop-clock - start-clock
}

MAIN.CPP
_______________________________________________________________________________________________________

// In Project 1, your are required to implement the code for bubble sort and optimized bubble sort
// using the data structure of sinngly linked list (nothing else).

/* Bubble Sort:
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
{
if (A[i] > A[j])
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}
}
*/

/* Optimized Bubble Sort:
flag = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < n-1; j++)
{
if (A[j] > A[j+1])
{
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
   flag = 1; // if swapping occurs
}
}
   if (flag == 0)
break; // the input list already sorted, no need for the inner loop
}
*/

// The main program will create 10 nodes for storing a sequence of 10 integers
// bubble Sort() will be invoked to sort these 10 integers
// then optimizedBubbleSort will be invoked to sort the sorted sequence (degenerate case) again
// You will find out optimizedBubbleSort will take O(1) running time to do the sorting
// unlike bubbleSort taking O(n^2) run time to sort a sorted sequence.

// Lastly, in order to see the differences of bubbleSort and optimizedBubbleSort,
// also implement timer into both code, after the sorting, print out the runtime
// of sorting the sequence. For bubbleSort, no matter sorted or unsorted, it always
// take O(n^2) runtime. But for optimizedBubbleSort, for unsorted sequence, like
// bubbleSort, it takes O(n^2) runtime. However, for a sorted sequence,
// optimizedBubbleSort will take O(1) only. For a sorted sequence as a
// degenerate case, optimizedBubbleSort is more efficienct than bubbleSort
// for sorting a sequence of integers.

// You MUST use this provided code for Project 1

#include <iostream>
using namespace std;

#include "node.h"
#include "singlylinkedlist.h"


int main()
{
   /* create 10 nodes */
   Node *n1 = new Node(23); // objects creation (class instantiation)
   Node *n2 = new Node(-20);
   Node *n3 = new Node(7);
   Node *n4 = new Node(174);
   Node *n5 = new Node(56);
   Node *n6 = new Node(-98);
   Node *n7 = new Node(101);
   Node *n8 = new Node(46);
   Node *n9 = new Node(31);
   Node *n10 = new Node(5);

   /* create singly linked list */
   singlyLinkedList *sLL;
   sLL = new singlyLinkedList();

   /* insert 10 nodes into the singly linked list in First in, Last out manner */
   sLL->addFront(n1);
   sLL->addFront(n2);
   sLL->addFront(n3);
   sLL->addFront(n4);
   sLL->addFront(n5);
   sLL->addFront(n6);
   sLL->addFront(n7);
   sLL->addFront(n8);
   sLL->addFront(n9);
   sLL->addFront(n10);

   /* display the contents of the 10 nodes in the singly linked list */
   sLL->displaySinglyLinkedList();

   /* The following code will act it is supposed to do
   when you are successfully implment bubbleSort and
   optimizedBubbleSort. */
   sLL->bubbleSort(); // bubble sort the unsorted sequence
   sLL->displaySinglyLinkedList(); // a sorted sequence displayed


   sLL->optimizedBubbleSort(); // optimized bubble sort the already sorted sequence (a degenerate case)
   // the runtime should show O(1), it means time should be musch less than runtime
   // of bubbleSort()
   sLL->displaySinglyLinkedList(); // a sorted sequence displayed

   system("PAUSE");
   return 0;
}

Solutions

Expert Solution

The changes has been made in 'singlylinkedlist.cpp' only.
So, C++ code of 'singlylinkedlist' is :

/* singlylinkedlist */

#include <iostream>
#include <time.h>
using namespace std;

#include "singlylinkedlist.h"

singlyLinkedList::singlyLinkedList()
{
   head = NULL;
}

singlyLinkedList::~singlyLinkedList()
{
}

void singlyLinkedList::addFront(Node *newNode)
{
   if (head == NULL)
       head = newNode;
   else
   {
       // Add code here!
       /* node1-->||| (before) what is after node2 --> node1 -->||| */

       newNode->next = head;
       head = newNode;
   };
}

void singlyLinkedList::displaySinglyLinkedList()
{
   Node *tempHead;

   tempHead = head;

   while (tempHead != NULL)
   {
       cout << tempHead->value << " ";
       tempHead = tempHead->next;
   }
   cout << endl;
}

void singlyLinkedList:: bubbleSort()
{
  time_t start, end;
  
  int n=0;
  Node *ptr = head;
  while(ptr)
  {
    n++;
    ptr = ptr->next;
  }

  Node *ptr2;
  ptr = head;
  ptr2 = ptr;
  int temp;
  time(&start);
  for (int i = 0; i < n; i++)
  {
    ptr = ptr2;
    for (int j = i; j < n; j++)
    {
      if (ptr2->value > ptr->value)
      {
        temp = ptr2->value;
        ptr2->value = ptr->value;
        ptr->value = temp;
      }
      ptr = ptr->next;
    }
    ptr2 = ptr2->next;
  }
    time(&end);
    cout << "\nBubble Sort time: " << difftime(end, start) << "sec\n";
}

void singlyLinkedList:: optimizedBubbleSort()
{
    time_t start, end;

  int n=0;
  Node *ptr = head;
  while(ptr)
  {
    n++;
    ptr = ptr->next;
  }

  Node *ptr2;
  ptr = head;
  ptr2 = ptr;
  time(&start);
   int flag = 0, temp;
    for (int i = 0; i < n; i++)
    {
      flag = 0;
      ptr = ptr2;
      for (int j = 0; j < n-1; j++)
      {
        if (ptr->value > ptr->next->value)
        {
          temp = ptr->value;
          ptr->value = ptr->next->value;
          ptr->next->value = temp;
           flag = 1; // if swapping occurs
        }
        ptr = ptr->next;
      }
     if (flag == 0)
        break; // the input list already sorted, no need for the inner loop
      ptr2 = ptr2->next;
    }
   time(&end);
   cout << "\nOptimezed Bubble Sort time: " << difftime(end, start) << "sec\n";
}

Output sample:

Note that time is 0 sec. This is because the size of data is very small so it takes almost no time to sort.

Hope it helps.


Related Solutions

Please use the code I provided!! Use either bubble sort or selection sort!! Thank you in...
Please use the code I provided!! Use either bubble sort or selection sort!! Thank you in advance This lab involves adding a sorting function to an existing C++ template. In this module, a file is provided for you -- SortableBag.h -- that implements a simple "bag" (unsorted collection of numbers) structure with array storage. Part 1 Add a sort() method to this template, which should not return any values or take any arguments ('void' for both the return type and...
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers....
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers. Record the time. Run Bubble Check time (compute the processing time) do it 100 times (random numbers) Take the average Insertion: Compare] (some explanations please)
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 let me know how to make code sort. If you put sort (sort 1000 6...
Please let me know how to make code sort. If you put sort (sort 1000 6 5 4 3 2 1, not separate), you will get 1 2 3 4 5 6 1000. sort 50 300 27 5 5 27 50 300 public static void main (String[] args) {        Scanner scnr = new Scanner(System.in);        String a = "";            a = scnr.nextLine();            String[] b = imput.split(" ") if (b[0].equalsI("sort")) { }...
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both...
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both are O(n^2) however it may be possible to classify one algorithm as being more efficient than the other. You are to discuss which algorithm you feel is the most efficient and in what cases it will be more efficient. Provide any relevant test cases and code to support your belief. Submit a pdf containing your findings and test results along with any relevant code...
How would I make it so that when I run my code it does not ask...
How would I make it so that when I run my code it does not ask for input (not having to enter after the statement and enter 0 for example) after ROXY (Forever ROXY Enterprises) appears? Like it would tell me the second statement right away along with the Roxy phrase. This is in C++. My code: #include / #include using std::endl; int main() {    void readAndConvert();    unsigned int stockSymbol;    unsigned int confNum;    std::cout << "ROXY...
1.   Bubble Sort Implement a bubble sort program that will read from a file “pp2.txt” from...
1.   Bubble Sort Implement a bubble sort program that will read from a file “pp2.txt” from the current directory a list of intergers (10 numbers to be exact), and the sort them, and print them to the screen. You can use redirection to read data from a given file through standard input, as opposed to reading the data from the file with the read API (similar to Lab #1). You can assume the input data will only have 10 numbers...
give a good explanation of Bubble sort, Insertion sort, Selection sort, and Quicksort.
give a good explanation of Bubble sort, Insertion sort, Selection sort, and Quicksort.
Sort the following set of numbers using bubble sort, insertion sort, and selection sort. Show the...
Sort the following set of numbers using bubble sort, insertion sort, and selection sort. Show the process step-by-step, and find the time complexity in Big-O notation for each method. For sorting, use ascending order. 49, 7, 60, 44, 18, 105
2 real-time examples on the Insertion sort, Bubble sort, Selection sort, Quick sort, Shell sort, Merge...
2 real-time examples on the Insertion sort, Bubble sort, Selection sort, Quick sort, Shell sort, Merge sort, Radix sort, Bucket sort, and Counting sort.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT