SlideShare a Scribd company logo
you will implement some sorting algorithms for arrays and linked lists.
Insertion Sort and Quicksort of an array
Implement the insertion sort and quicksort for an integer array. The functions are defined in the
"sorting.h" header file.
/**
* @brief Insertion sort algorithm
* @param array Array to be sorted. The array is modified in place.
* @param lowindex Lowest index of the array
* @param highindex Highest index of the array
* @param reversed If reversed = true, the array should be sorted in descending order, otherwise
in ascending order
*/
void insertionSort(int array[], int lowindex, int highindex, bool reversed = false);
and
**
* @brief Quick sort algorithm
*
* @param array Array to be sorted. The array is modified in place.
* @param lowindex Lowest index of the array
* @param highindex Highest index of the array
* @param reversed If reversed = true, the array should be sorted in descending order, otherwise
in ascending order
*/
void quickSort(int array[], int lowindex, int highindex, bool reversed = false);
The array should be sorted in place. Compared to the examples in the textbook, those functions
have an additional parameter reversed. If reversed = true, the array should be sorted in
descending order, otherwise in ascending order. You should complete the implementations of
those two functions in the "sorting_basic.cpp" file.
A better quicksort algorithm
Quicksort is a very fast comparison sorting algorithm, especially wheb the array or list gets large.
However, when the arrays/lists are small enough, quicksort may run slower than some of the
(n^2) algorithms. This might not seem important until you note that when sorting a large array
with quicksort, many small sublists must be sorted. While the savings on sorting one small list
with a faster algorithm might be negligible, sorting hundreds of small lists with a faster algorithm
can make a difference in the overall efficiency of the sort. For this part of the assignment, you
will combine quicksort with another sorting algorithm to build a faster sorting algorithm. One
option is to
use quicksort until the array/list gets small enough, and then use insertion sort or another sort to
sort the small arrays/lists
What does "small enough" mean? You can try a percentage of the list (say, 5% or 10%), or an
absolute number (5 elements, 8 elements, 10 elements, 15 elements, 100 elements, etc), or
something else of your choosing. Based on your tests, choose the one that is the most efficient.
You should also tests to ensure that your hybrid quicksort has reasonable performance on all lists
-- most notably, it should be efficient on sorted and inverse sorted lists as well as random lists.
The definition of the hybrid quicksort function is as the following:
/**
* @brief A hybrid of insertion sort and quick sort algorithm. The algorithm is based on the idea
that if the array is short, it is better to use insertion sort.
* It uses quicksort until the list gets small enough, and then uses insertion sort or another sort to
sort the small lists
*
* @param array The array to be sorted. The array is modified in place.
* @param lowindex The lowest index of the array
* @param highindex The highest index of the array
* @param reversed if reversed = true, the array should be sorted in descending order, otherwise
in ascending order
*/
void hybridQuickSort(int array[], int lowindex, int highindex, bool reversed = false);
The implementation of the function should be included in the "sorting_hybrid.cpp" file. The
array is sorted in place. The program test3 tests the performance of insert sort, quicksort, and
hybrid quicksort for an array with 100,000 numbers. Try to test and adjust your hybrid quicksort
implementation to beat the performance of regular quicksort.
Sorting a linked list
Implement the insertion sort and merge sort for a linked list of integer values.The definitions of
the functions are as the following.
/**
* @brief Insertion sort algorithm for linked lists
*
* @param list Input linked list
* @param reversed if reversed = true, the list should be sorted in descending order, otherwise in
ascending order
* @return LinkedList Sorted linked list
*/
LinkedList insertionSortLL(const LinkedList& list, bool reversed = false);
and
/**
* @brief Merge sort algorithm for linked lists
*
* @param list Input linked list
* @param reversed if reversed = true, the list should be sorted in descending order, otherwise in
ascending order
* @return LinkedList Sorted linked list
*/
LinkedList mergeSortLL(const LinkedList& list, bool reversed = false);
You should complete the implementations of those two functions in the "sorting_ll.cpp" file. The
input linked list isn't modified. Instead, a new linked list with numbers in sorted order should be
returned. copy code of the LinkedList class. The insertionSortLL and mergeSortLL are declared
as friend functions of the LinkedList class.
code should work correctly for all tests and be robust for potential error conditions, and free of
dangerous code constructs and memory leaks.
We will use tools like cppcheckLinks to an external site. and valgrind
Linklist.h
Linkedlist.cpp
sorting_basic.cpp
sorting_ll.cpp
sorting_hybrid.cpp
What i have
#include "LinkedList.h"
using namespace std;
LinkedList insertionSortLL(const LinkedList& list, bool reversed = false) {
// Create a new linked list to store the sorted results.
LinkedList sortedList;
// Iterate over the input linked list.
for (Node* node = list.front; node != nullptr; node = node->next) {
// Insert the current node into the sorted linked list.
sortedList.insertAt(sortedList.search(node->val), node->val);
}
// Return the sorted linked list.
return sortedList;
}
LinkedList mergeSortLL(const LinkedList& list, bool reversed = false) {
// If the linked list is empty or has only one node, it is already sorted.
if (list.isEmpty() || list.length() <= 1) {
return list;
}
// Split the linked list into two halves.
LinkedList leftList = mergeSortLL(list.sublist(0, list.length() / 2), reversed);
LinkedList rightList = mergeSortLL(list.sublist(list.length() / 2, list.length()), reversed);
// Merge the two sorted halves into a new linked list.
return mergeLinkedList(leftList, rightList, reversed);
}
// Merges two sorted linked lists into a new linked list.
LinkedList mergeLinkedList(const LinkedList& leftList, const LinkedList& rightList, bool
reversed = false) {
LinkedList sortedList;
// Create two pointers to the current nodes in the two linked lists.
Node* leftNode = leftList.front;
Node* rightNode = rightList.front;
// While both linked lists have nodes, compare the current nodes and add the smaller node to the
sorted linked list.
while (leftNode != nullptr && rightNode != nullptr) {
if (reversed) {
if (leftNode->val > rightNode->val) {
sortedList.insertAt(sortedList.length(), rightNode->val);
rightNode = rightNode->next;
} else {
sortedList.insertAt(sortedList.length(), leftNode->val);
leftNode = leftNode->next;
}
} else {
if (leftNode->val < rightNode->val) {
sortedList.insertAt(sortedList.length(), leftNode->val);
leftNode = leftNode->next;
} else {
sortedList.insertAt(sortedList.length(), rightNode->val);
rightNode = rightNode->next;
}
}
}
// Add any remaining nodes from the left or right linked list to the sorted linked list.
while (leftNode != nullptr) {
sortedList.insertAt(sortedList.length(), leftNode->val);
leftNode = leftNode->next;
}
while (rightNode != nullptr) {
sortedList.insertAt(sortedList.length(), rightNode->val);
rightNode = rightNode->next;
}
// Return the sorted linked list.
return sortedList;
} // Compiler: g++ // File type: headher file linkedlist.h // Datatype T : element type definition
typedef int T;// int for now but can change later //a list node is defined here as a struct Node for
now struct Node { T val; // stored value Node *next; // pointer to the next node // Constructor
Node (T val =0, Node next = nullptr ){ this > val = val; this->next = next; } [}; // class
LinkedList { private: Node *front; // pointer to the front node Node *rear; // pointer to the rear
node int count; // the number of nodes in the list public: LinkedList() {// constructor to create an
empty list front = nullptr; rear = nullptr; count =0; } LinkedList(); // destructor to destroy all
nodes and release memory / @brief Copy Constructor to allow pass by value and return by value
of a LinkedList @param other LinkedList to be copied ; / LinkedList(const LinkedList &other);
Miscellaneous Files (Global Scope) @brief You will implement the insertion sort and merge sort
algorithms for a linked list in this file : // You must complete the TODO parts and then complete
LinkedList.cpp. Delete "TODO" after you are done. [//You should always comments to each
function to describe its PURPOSE and PARAMETERS #include "sorting.h" / * Implement the
insertion sort algorithm for Linkedlist correctly LinkedList insertionSortLL(const LinkedList&
list, bool reversed) { // TODO: Add your code here / : Implement the merge sort algorithm for
LinkedList correctly LinkedList mergeSortLL(const LinkedList& list, bool reversed) { //
TODO: Add your code here
* Implemention of selected sorting algorithms @file sorting.cpp #include "sorting.h" /:
Implement the insertionSort algorithm correctly / void insertionSort(int array[], int lowindex, int
highindex, bool reversed) { // TODO: Add your code here [} / @brief Implementation of the
partition function used by quick sort int partition(int array[], int lowindex, int highindex, bool
reversed) { // TODO: Add your code here /1 Implement the quickSort algorithm correctly void
quickSort(int array[], int lowindex, int highindex, bool reversed) { // TODO: Add your code
here
@brief You will implement the "optimized" quick sort algorithms for a linked list in this file //
You must complete the TODO parts and then complete LinkedList.cpp. Delete "TODO" after
you are done. [//You should always comments to each function to describe its PURPOSE and
PARAMETERS #include "sorting.h" / : Implement a hybrid of insertion sort and quick sort
algorithm. The algorithm is based on the idea that if the array is short, * it is better to use
insertion sort. * It uses quicksort until the list gets small enough, and then uses insertion sort or
another sort to sort the small lists / void hybridQuickSort(int array[], int lowindex, int highindex,
bool reversed) { // TODO: Add your code here
Files (Global Scope) / @brief Insert a value at a specified position in the list. The valid pos is in
the range of 0 to count. The value will be inserted before the node at the specified position. if pos
=0, the value will be inserte at the front of the list. if pos = count, the value will be inserted at the
rear of the list. @param pos: position to insert the value at. @param val: value to insert. @return
true: if the value was inserted. @return false: if the value was not inserted because pos is out of
the range. i*/ bool insertAt(int pos, T val); / @brief check whether a value is in the list or not
@param val @return int: the position of the value in the list. If the value is not in the list, return -
1. */ int search(const T& val) const; / @brief Assume two linked lists that represent Set A and
Set B respectively. Compute the union AUB and return the result as a new linked list. @param
LA Input linkedlist A as a set (no duplicated element) @param LB Input linkedlist B as a set (no
duplicated element) @return LinkedList* return the linkedlist of the union 1 friend LinkedList
unionLinkedList(const LinkedList& LA, const LinkedList& LB); / @brief Assume two input
linked lists, LA and LB, whose elements are both in the non-descending order. * This function
merges LA and LB into a new linked list (as the return value). * The elements in the new list
should still be in the non-descending order. @param LA @param LB @return LinkedList i*/
friend LinkedList mergeLinkedList(const LinkedList& LA, const LinkedList& LB); / @brief
Insertion sort algorithm for linked lists declare it as friend function of the LinkedList class to
access private variables / friend LinkedList insertionSortLL(const LinkedList& list, bool
reversed); / @brief Merge sort algorithm for linked lists declare it as friend function of the
LinkedList class to access private variables */ friend LinkedList mergeSortLL(const
LinkedList& list, bool reversed);
cellaneous Files (Global Scope) @brief The implementation of the Linked List data structure //
must complete the TODO parts and then complete LinkedList.cpp. Delete "TODO" after you are
don //- Make sure description and PARAMETER comments are given in detail // Add sufficient
comments to your code body to describe what it does. // - Make sure al1 if-then-else are
commented describing which case it is // - Make sure all local variables are described fully with
their purposes # include #include"linkedlist.h" using namespace std; / @brief Destructor to
destroy all nodes and release memory i*/ LinkedList: : LinkedList() { //TODO: Add code here.
Make sure memory is released properly. / @brief Purpose: Checks if the list is empty @return
true if the list is empty, false otherwise / bool LinkedList: : isEmpty() const { // TODO: Add
code here / @brief Get the number of nodes in the list (0return int The number of nodes in the
list i*/ int LinkedList: : length() const { //TODO: Add code here 1/ @brief Convert the list to a
string / string LinkedList: :tostring() { string str = "["; Node ptr = front; if (ptr != nullptr) { //
Head node is not preceded by separator
ieous Files (Global Scope) * @brief Overloading of = (returns a reference to a LinkedList)
(@param other LinkedList to be copied (@return reference to a LinkedList :/ LinkedList
&operator=(const LinkedList &other); i* @brief Overloading of = (returns a reference to a
LinkedList) * @param other LinkedList to be copied * @return reference to a LinkedList /
LinkedList &operator=(const LinkedList &other); / @brief Purpose: Checks if the list is empty
@return true if the list is empty, false otherwise */ bool isEmpty() const; / @brief Get the
number of nodes in the list @return int The number of nodes in the list */ int length() const; /
@brief Convert the contents of the list to a string i*/ string tostring(); / @brief Displays the
contents of the list / void displayAll(); //TODO: Add comments void addFront(T val); //TODO:
Add comments void addRear(T val); //TODO: Add comments bool deletefront(T &val);
//TODO: Add comments bool deleteRear(T &val); / * @brief Delete a node at a given position
from the list. The * node at position pos is deleted and the value of the deleted node is returned
in val. * The valid range of pos is 0 to count -1 . pos =0 is the first node, and pos = count-1 is the
last node * @param pos: position of the node to be deleted * @param val: it is set to the value of
the node to be deleted * @return true: if the node was deleted successfully * @return false: if the
node was not deleted successfully because the position was out of range */ bool deleteAt(int pos,
T &val);
ellaneous Files str += to_string (ptr>val); ptr = ptr->next; } while (ptr != nullptr) { str +="," +
to_string(ptr->val); ptr = ptr->next; } str += "]"; return str; / @brief Displays the contents of the
list void LinkedList: :displayAll() { cout tostring() endl; } //TODO: Add comments void
LinkedList: : addRear(T val) { // TODO: Add code here // consider the two cases of whether the
list was empty [3 //TODO: Add comments void LinkedList: :addFront( T val) { // TODO: Add
code here // consider the two cases of whether the list was empty //TODO: Add comments bool
LinkedList: :deleteFront(T &oldNum) { // TODO: Add code here // consider if the list was
empty and return false if the list is empty // consider the special case of deleting the only node in
the list //TODO: Add comments bool LinkedList: : deleteRear(T &oldNum) { // TODO: Add
code here // consider if the list was empty and return false if the list is empty // consider the
special case of deleting the only node in the list /* -.- harder ones for test 2 and 3 -. */ /** *
Implement the deleteAt function to delete a node at a given position. */ bool LinkedList:
:deleteAt(int pos, T &val) { //TODO: Add code here // check if the pos is valid first, then move
the ptr to the rigth positon // consider the special case of deleting the first node and the last node
// Do not forget to set value.
:llaneous Files (Global Scope) [ij/***Implementtheinsertatfunctionhere.*/ bool LinkedList:
insertAt(int pos, T val) { //TODO: Add code here // check if the pos is valid first, then move the
ptr to the rigth positon // consider the special case of inserting the first node and the last node /
@brief Copy Constructor to allow pass by value and return by value of a LinkedList @param
other LinkedList to be copied ; / inkedList: : LinkedList(const LinkedList &other) { // Start
with an empty list front = nullptr; rear = nullptr; count =0; // TODO: Add code here. Interate
through the other list and add a new node to this list // for each node in the other list. The new
node should have the same value as the other node. @brief Overloading of = (returns a reference
to a LinkedList) @param other LinkedList to be copied @return reference to a LinkedList
inkedList& LinkedList: :operator=(const LinkedList &other) { if(this != &other ){// check if
the same object // Delete all nodes in this list // TODO: Add code here // Interate through the
other list and add a new node to this list //Be sure to set the front and rear pointers to the correct
values // Be sure to set the count to the correct value // TODO: Add code here } return *this; /
Implement the search function. @return int: the position of the value in the list. If the value is not
in the list, return -1. */ int LinkedList: :search(const T& val) const { // TODO: Add code here
to complete the search function return -1 ;

More Related Content

PDF
you will implement some sorting algorithms for arrays and linked lis.pdf
PDF
Write a java class LIST that outputsmainpublic class Ass.pdf
PPT
1 list datastructures
DOCX
Please solve the following problem using C++- Thank you Instructions-.docx
DOCX
hello- please dont just copy from other answers- the following is the.docx
PDF
There are a couple of new methods that you will be writing for this pr.pdf
DOCX
When we first examined the array based and node based implementations.docx
PPT
Md08 collection api
you will implement some sorting algorithms for arrays and linked lis.pdf
Write a java class LIST that outputsmainpublic class Ass.pdf
1 list datastructures
Please solve the following problem using C++- Thank you Instructions-.docx
hello- please dont just copy from other answers- the following is the.docx
There are a couple of new methods that you will be writing for this pr.pdf
When we first examined the array based and node based implementations.docx
Md08 collection api

Similar to you will implement some sorting algorithms for arrays and linked lis.pdf (20)

PDF
In this assignment you will implement insert() method for a singly l.pdf
PDF
Recursion Lecture in C++
PDF
Need to be done in C Please Sorted number list implementation with.pdf
PPTX
data structures and algorithms Unit 3
PPTX
Advance excel
PPT
Java Collections Framework
PDF
Please the following is the currency class of perious one- class Curre.pdf
PDF
DSA UNIT II ARRAY AND LIST - notes
PDF
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
PPT
2 a stacks
PDF
Need to be done in C++ Please Sorted number list implementation wit.pdf
PPTX
Computer programming 2 Lesson 13
PPT
Generics Collections
PPTX
Data Structure
PDF
Everything needs to be according to the instructions- thank you! SUPPO.pdf
PPTX
Merge radix-sort-algorithm
PPTX
Merge radix-sort-algorithm
PDF
In C++Add the function min as an abstract function to the classar.pdf
DOCX
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
In this assignment you will implement insert() method for a singly l.pdf
Recursion Lecture in C++
Need to be done in C Please Sorted number list implementation with.pdf
data structures and algorithms Unit 3
Advance excel
Java Collections Framework
Please the following is the currency class of perious one- class Curre.pdf
DSA UNIT II ARRAY AND LIST - notes
Inspect the class declaration for a doubly-linked list node in Node-h-.pdf
2 a stacks
Need to be done in C++ Please Sorted number list implementation wit.pdf
Computer programming 2 Lesson 13
Generics Collections
Data Structure
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Merge radix-sort-algorithm
Merge radix-sort-algorithm
In C++Add the function min as an abstract function to the classar.pdf
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Ad

More from info335653 (12)

PDF
You�ve been hired by the local government to determine which employe.pdf
PDF
You are the chief data scientist of the marketing company �VisualZ.�.pdf
PDF
Write a program that displays a table of the Celsius temperatures 0 .pdf
PDF
Why is the release of GDP statistics less interesting to investors t.pdf
PDF
Winds of Change in Klickitat CountyThe Harvest Wind ProjectM..pdf
PDF
With reference to the case study, define social media marketing and cr.pdf
PDF
Will upvote Please fix the following code and post your inputs and o.pdf
PDF
Which of the following statements is CORRECT a. The four most importa.pdf
PDF
We will discuss 1. IT systems� complexity IT systems have become unman.pdf
PDF
usingpackage util;import java.util.;This class implements.pdf
PDF
Using MISP VM ova file, import it on VirtualBox and respond to the q.pdf
PDF
True or false Public policy is not an important component of organi.pdf
You�ve been hired by the local government to determine which employe.pdf
You are the chief data scientist of the marketing company �VisualZ.�.pdf
Write a program that displays a table of the Celsius temperatures 0 .pdf
Why is the release of GDP statistics less interesting to investors t.pdf
Winds of Change in Klickitat CountyThe Harvest Wind ProjectM..pdf
With reference to the case study, define social media marketing and cr.pdf
Will upvote Please fix the following code and post your inputs and o.pdf
Which of the following statements is CORRECT a. The four most importa.pdf
We will discuss 1. IT systems� complexity IT systems have become unman.pdf
usingpackage util;import java.util.;This class implements.pdf
Using MISP VM ova file, import it on VirtualBox and respond to the q.pdf
True or false Public policy is not an important component of organi.pdf
Ad

Recently uploaded (20)

PPTX
Software Engineering BSC DS UNIT 1 .pptx
PDF
English Language Teaching from Post-.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
IMMUNIZATION PROGRAMME pptx
PPTX
Introduction and Scope of Bichemistry.pptx
PPTX
Presentation on Janskhiya sthirata kosh.
PDF
High Ground Student Revision Booklet Preview
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PPTX
Onica Farming 24rsclub profitable farm business
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
PPTX
ACUTE NASOPHARYNGITIS. pptx
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PPTX
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
PPTX
Odoo 18 Sales_ Managing Quotation Validity
PDF
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
PDF
Sunset Boulevard Student Revision Booklet
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
PPTX
Strengthening open access through collaboration: building connections with OP...
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
Software Engineering BSC DS UNIT 1 .pptx
English Language Teaching from Post-.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
IMMUNIZATION PROGRAMME pptx
Introduction and Scope of Bichemistry.pptx
Presentation on Janskhiya sthirata kosh.
High Ground Student Revision Booklet Preview
How to Manage Loyalty Points in Odoo 18 Sales
Onica Farming 24rsclub profitable farm business
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
ACUTE NASOPHARYNGITIS. pptx
Open Quiz Monsoon Mind Game Final Set.pptx
COMPUTERS AS DATA ANALYSIS IN PRECLINICAL DEVELOPMENT.pptx
Odoo 18 Sales_ Managing Quotation Validity
LDMMIA Reiki Yoga S2 L3 Vod Sample Preview
Sunset Boulevard Student Revision Booklet
Week 4 Term 3 Study Techniques revisited.pptx
Skill Development Program For Physiotherapy Students by SRY.pptx
Strengthening open access through collaboration: building connections with OP...
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf

you will implement some sorting algorithms for arrays and linked lis.pdf

  • 1. you will implement some sorting algorithms for arrays and linked lists. Insertion Sort and Quicksort of an array Implement the insertion sort and quicksort for an integer array. The functions are defined in the "sorting.h" header file. /** * @brief Insertion sort algorithm * @param array Array to be sorted. The array is modified in place. * @param lowindex Lowest index of the array * @param highindex Highest index of the array * @param reversed If reversed = true, the array should be sorted in descending order, otherwise in ascending order */ void insertionSort(int array[], int lowindex, int highindex, bool reversed = false); and ** * @brief Quick sort algorithm * * @param array Array to be sorted. The array is modified in place. * @param lowindex Lowest index of the array * @param highindex Highest index of the array * @param reversed If reversed = true, the array should be sorted in descending order, otherwise in ascending order */ void quickSort(int array[], int lowindex, int highindex, bool reversed = false); The array should be sorted in place. Compared to the examples in the textbook, those functions have an additional parameter reversed. If reversed = true, the array should be sorted in descending order, otherwise in ascending order. You should complete the implementations of those two functions in the "sorting_basic.cpp" file. A better quicksort algorithm Quicksort is a very fast comparison sorting algorithm, especially wheb the array or list gets large. However, when the arrays/lists are small enough, quicksort may run slower than some of the (n^2) algorithms. This might not seem important until you note that when sorting a large array with quicksort, many small sublists must be sorted. While the savings on sorting one small list with a faster algorithm might be negligible, sorting hundreds of small lists with a faster algorithm can make a difference in the overall efficiency of the sort. For this part of the assignment, you
  • 2. will combine quicksort with another sorting algorithm to build a faster sorting algorithm. One option is to use quicksort until the array/list gets small enough, and then use insertion sort or another sort to sort the small arrays/lists What does "small enough" mean? You can try a percentage of the list (say, 5% or 10%), or an absolute number (5 elements, 8 elements, 10 elements, 15 elements, 100 elements, etc), or something else of your choosing. Based on your tests, choose the one that is the most efficient. You should also tests to ensure that your hybrid quicksort has reasonable performance on all lists -- most notably, it should be efficient on sorted and inverse sorted lists as well as random lists. The definition of the hybrid quicksort function is as the following: /** * @brief A hybrid of insertion sort and quick sort algorithm. The algorithm is based on the idea that if the array is short, it is better to use insertion sort. * It uses quicksort until the list gets small enough, and then uses insertion sort or another sort to sort the small lists * * @param array The array to be sorted. The array is modified in place. * @param lowindex The lowest index of the array * @param highindex The highest index of the array * @param reversed if reversed = true, the array should be sorted in descending order, otherwise in ascending order */ void hybridQuickSort(int array[], int lowindex, int highindex, bool reversed = false); The implementation of the function should be included in the "sorting_hybrid.cpp" file. The array is sorted in place. The program test3 tests the performance of insert sort, quicksort, and hybrid quicksort for an array with 100,000 numbers. Try to test and adjust your hybrid quicksort implementation to beat the performance of regular quicksort. Sorting a linked list Implement the insertion sort and merge sort for a linked list of integer values.The definitions of the functions are as the following. /** * @brief Insertion sort algorithm for linked lists * * @param list Input linked list * @param reversed if reversed = true, the list should be sorted in descending order, otherwise in ascending order
  • 3. * @return LinkedList Sorted linked list */ LinkedList insertionSortLL(const LinkedList& list, bool reversed = false); and /** * @brief Merge sort algorithm for linked lists * * @param list Input linked list * @param reversed if reversed = true, the list should be sorted in descending order, otherwise in ascending order * @return LinkedList Sorted linked list */ LinkedList mergeSortLL(const LinkedList& list, bool reversed = false); You should complete the implementations of those two functions in the "sorting_ll.cpp" file. The input linked list isn't modified. Instead, a new linked list with numbers in sorted order should be returned. copy code of the LinkedList class. The insertionSortLL and mergeSortLL are declared as friend functions of the LinkedList class. code should work correctly for all tests and be robust for potential error conditions, and free of dangerous code constructs and memory leaks. We will use tools like cppcheckLinks to an external site. and valgrind Linklist.h Linkedlist.cpp sorting_basic.cpp
  • 4. sorting_ll.cpp sorting_hybrid.cpp What i have #include "LinkedList.h" using namespace std; LinkedList insertionSortLL(const LinkedList& list, bool reversed = false) { // Create a new linked list to store the sorted results. LinkedList sortedList; // Iterate over the input linked list. for (Node* node = list.front; node != nullptr; node = node->next) { // Insert the current node into the sorted linked list. sortedList.insertAt(sortedList.search(node->val), node->val); } // Return the sorted linked list. return sortedList; } LinkedList mergeSortLL(const LinkedList& list, bool reversed = false) { // If the linked list is empty or has only one node, it is already sorted. if (list.isEmpty() || list.length() <= 1) { return list; } // Split the linked list into two halves. LinkedList leftList = mergeSortLL(list.sublist(0, list.length() / 2), reversed); LinkedList rightList = mergeSortLL(list.sublist(list.length() / 2, list.length()), reversed); // Merge the two sorted halves into a new linked list. return mergeLinkedList(leftList, rightList, reversed); } // Merges two sorted linked lists into a new linked list. LinkedList mergeLinkedList(const LinkedList& leftList, const LinkedList& rightList, bool reversed = false) {
  • 5. LinkedList sortedList; // Create two pointers to the current nodes in the two linked lists. Node* leftNode = leftList.front; Node* rightNode = rightList.front; // While both linked lists have nodes, compare the current nodes and add the smaller node to the sorted linked list. while (leftNode != nullptr && rightNode != nullptr) { if (reversed) { if (leftNode->val > rightNode->val) { sortedList.insertAt(sortedList.length(), rightNode->val); rightNode = rightNode->next; } else { sortedList.insertAt(sortedList.length(), leftNode->val); leftNode = leftNode->next; } } else { if (leftNode->val < rightNode->val) { sortedList.insertAt(sortedList.length(), leftNode->val); leftNode = leftNode->next; } else { sortedList.insertAt(sortedList.length(), rightNode->val); rightNode = rightNode->next; } } } // Add any remaining nodes from the left or right linked list to the sorted linked list. while (leftNode != nullptr) { sortedList.insertAt(sortedList.length(), leftNode->val); leftNode = leftNode->next; } while (rightNode != nullptr) { sortedList.insertAt(sortedList.length(), rightNode->val); rightNode = rightNode->next; } // Return the sorted linked list. return sortedList;
  • 6. } // Compiler: g++ // File type: headher file linkedlist.h // Datatype T : element type definition typedef int T;// int for now but can change later //a list node is defined here as a struct Node for now struct Node { T val; // stored value Node *next; // pointer to the next node // Constructor Node (T val =0, Node next = nullptr ){ this > val = val; this->next = next; } [}; // class LinkedList { private: Node *front; // pointer to the front node Node *rear; // pointer to the rear node int count; // the number of nodes in the list public: LinkedList() {// constructor to create an empty list front = nullptr; rear = nullptr; count =0; } LinkedList(); // destructor to destroy all nodes and release memory / @brief Copy Constructor to allow pass by value and return by value of a LinkedList @param other LinkedList to be copied ; / LinkedList(const LinkedList &other); Miscellaneous Files (Global Scope) @brief You will implement the insertion sort and merge sort algorithms for a linked list in this file : // You must complete the TODO parts and then complete LinkedList.cpp. Delete "TODO" after you are done. [//You should always comments to each function to describe its PURPOSE and PARAMETERS #include "sorting.h" / * Implement the insertion sort algorithm for Linkedlist correctly LinkedList insertionSortLL(const LinkedList& list, bool reversed) { // TODO: Add your code here / : Implement the merge sort algorithm for LinkedList correctly LinkedList mergeSortLL(const LinkedList& list, bool reversed) { // TODO: Add your code here * Implemention of selected sorting algorithms @file sorting.cpp #include "sorting.h" /:
  • 7. Implement the insertionSort algorithm correctly / void insertionSort(int array[], int lowindex, int highindex, bool reversed) { // TODO: Add your code here [} / @brief Implementation of the partition function used by quick sort int partition(int array[], int lowindex, int highindex, bool reversed) { // TODO: Add your code here /1 Implement the quickSort algorithm correctly void quickSort(int array[], int lowindex, int highindex, bool reversed) { // TODO: Add your code here @brief You will implement the "optimized" quick sort algorithms for a linked list in this file // You must complete the TODO parts and then complete LinkedList.cpp. Delete "TODO" after you are done. [//You should always comments to each function to describe its PURPOSE and PARAMETERS #include "sorting.h" / : Implement a hybrid of insertion sort and quick sort algorithm. The algorithm is based on the idea that if the array is short, * it is better to use insertion sort. * It uses quicksort until the list gets small enough, and then uses insertion sort or another sort to sort the small lists / void hybridQuickSort(int array[], int lowindex, int highindex, bool reversed) { // TODO: Add your code here Files (Global Scope) / @brief Insert a value at a specified position in the list. The valid pos is in the range of 0 to count. The value will be inserted before the node at the specified position. if pos =0, the value will be inserte at the front of the list. if pos = count, the value will be inserted at the rear of the list. @param pos: position to insert the value at. @param val: value to insert. @return true: if the value was inserted. @return false: if the value was not inserted because pos is out of the range. i*/ bool insertAt(int pos, T val); / @brief check whether a value is in the list or not @param val @return int: the position of the value in the list. If the value is not in the list, return - 1. */ int search(const T& val) const; / @brief Assume two linked lists that represent Set A and Set B respectively. Compute the union AUB and return the result as a new linked list. @param LA Input linkedlist A as a set (no duplicated element) @param LB Input linkedlist B as a set (no duplicated element) @return LinkedList* return the linkedlist of the union 1 friend LinkedList unionLinkedList(const LinkedList& LA, const LinkedList& LB); / @brief Assume two input linked lists, LA and LB, whose elements are both in the non-descending order. * This function merges LA and LB into a new linked list (as the return value). * The elements in the new list should still be in the non-descending order. @param LA @param LB @return LinkedList i*/ friend LinkedList mergeLinkedList(const LinkedList& LA, const LinkedList& LB); / @brief Insertion sort algorithm for linked lists declare it as friend function of the LinkedList class to access private variables / friend LinkedList insertionSortLL(const LinkedList& list, bool reversed); / @brief Merge sort algorithm for linked lists declare it as friend function of the LinkedList class to access private variables */ friend LinkedList mergeSortLL(const
  • 8. LinkedList& list, bool reversed); cellaneous Files (Global Scope) @brief The implementation of the Linked List data structure // must complete the TODO parts and then complete LinkedList.cpp. Delete "TODO" after you are don //- Make sure description and PARAMETER comments are given in detail // Add sufficient comments to your code body to describe what it does. // - Make sure al1 if-then-else are commented describing which case it is // - Make sure all local variables are described fully with their purposes # include #include"linkedlist.h" using namespace std; / @brief Destructor to destroy all nodes and release memory i*/ LinkedList: : LinkedList() { //TODO: Add code here. Make sure memory is released properly. / @brief Purpose: Checks if the list is empty @return true if the list is empty, false otherwise / bool LinkedList: : isEmpty() const { // TODO: Add code here / @brief Get the number of nodes in the list (0return int The number of nodes in the list i*/ int LinkedList: : length() const { //TODO: Add code here 1/ @brief Convert the list to a string / string LinkedList: :tostring() { string str = "["; Node ptr = front; if (ptr != nullptr) { // Head node is not preceded by separator ieous Files (Global Scope) * @brief Overloading of = (returns a reference to a LinkedList) (@param other LinkedList to be copied (@return reference to a LinkedList :/ LinkedList &operator=(const LinkedList &other); i* @brief Overloading of = (returns a reference to a LinkedList) * @param other LinkedList to be copied * @return reference to a LinkedList / LinkedList &operator=(const LinkedList &other); / @brief Purpose: Checks if the list is empty @return true if the list is empty, false otherwise */ bool isEmpty() const; / @brief Get the number of nodes in the list @return int The number of nodes in the list */ int length() const; / @brief Convert the contents of the list to a string i*/ string tostring(); / @brief Displays the contents of the list / void displayAll(); //TODO: Add comments void addFront(T val); //TODO: Add comments void addRear(T val); //TODO: Add comments bool deletefront(T &val); //TODO: Add comments bool deleteRear(T &val); / * @brief Delete a node at a given position from the list. The * node at position pos is deleted and the value of the deleted node is returned in val. * The valid range of pos is 0 to count -1 . pos =0 is the first node, and pos = count-1 is the last node * @param pos: position of the node to be deleted * @param val: it is set to the value of the node to be deleted * @return true: if the node was deleted successfully * @return false: if the node was not deleted successfully because the position was out of range */ bool deleteAt(int pos, T &val); ellaneous Files str += to_string (ptr>val); ptr = ptr->next; } while (ptr != nullptr) { str +="," + to_string(ptr->val); ptr = ptr->next; } str += "]"; return str; / @brief Displays the contents of the
  • 9. list void LinkedList: :displayAll() { cout tostring() endl; } //TODO: Add comments void LinkedList: : addRear(T val) { // TODO: Add code here // consider the two cases of whether the list was empty [3 //TODO: Add comments void LinkedList: :addFront( T val) { // TODO: Add code here // consider the two cases of whether the list was empty //TODO: Add comments bool LinkedList: :deleteFront(T &oldNum) { // TODO: Add code here // consider if the list was empty and return false if the list is empty // consider the special case of deleting the only node in the list //TODO: Add comments bool LinkedList: : deleteRear(T &oldNum) { // TODO: Add code here // consider if the list was empty and return false if the list is empty // consider the special case of deleting the only node in the list /* -.- harder ones for test 2 and 3 -. */ /** * Implement the deleteAt function to delete a node at a given position. */ bool LinkedList: :deleteAt(int pos, T &val) { //TODO: Add code here // check if the pos is valid first, then move the ptr to the rigth positon // consider the special case of deleting the first node and the last node // Do not forget to set value. :llaneous Files (Global Scope) [ij/***Implementtheinsertatfunctionhere.*/ bool LinkedList: insertAt(int pos, T val) { //TODO: Add code here // check if the pos is valid first, then move the ptr to the rigth positon // consider the special case of inserting the first node and the last node / @brief Copy Constructor to allow pass by value and return by value of a LinkedList @param other LinkedList to be copied ; / inkedList: : LinkedList(const LinkedList &other) { // Start with an empty list front = nullptr; rear = nullptr; count =0; // TODO: Add code here. Interate through the other list and add a new node to this list // for each node in the other list. The new node should have the same value as the other node. @brief Overloading of = (returns a reference to a LinkedList) @param other LinkedList to be copied @return reference to a LinkedList inkedList& LinkedList: :operator=(const LinkedList &other) { if(this != &other ){// check if the same object // Delete all nodes in this list // TODO: Add code here // Interate through the other list and add a new node to this list //Be sure to set the front and rear pointers to the correct values // Be sure to set the count to the correct value // TODO: Add code here } return *this; / Implement the search function. @return int: the position of the value in the list. If the value is not in the list, return -1. */ int LinkedList: :search(const T& val) const { // TODO: Add code here to complete the search function return -1 ;