I need help with implementing a bubblesort function in c++. Also, the cpp and .h
ID: 3565914 • Letter: I
Question
I need help with implementing a bubblesort function in c++. Also, the cpp and .h are included
===================== part2.h ===================== #ifndef CSC116_A3_PART2_H_ #define CSC116_A3_PART2_H_ #include <iostream> #include <list> #include <vector> using namespace std; // In C++, you can have multiple functions of the same name // provided that the number and type of arguments are different. /* * Perform an in-place sort of the list l using the * bubble sort algorithm. * * Pre-conditions: * l.size() >= 1 * * Examples: * if l is {2,1,4}, after bubble_sort(l), l is {1,2,4} * if l is {1}, after bubble_sort(l), l is {1} */ void bubble_sort (list<int> &l); /* * Perform an in-place sort of the vector v using the * bubble sort algorithm. * * Pre-conditions: * v.size() >= 1 * * Examples: * if v is {2,1,4}, after bubble_sort(v), v is {1,2,4} * if v is {1}, after bubble_sort(v), v is {1} */ void bubble_sort (vector<int> &v); #endif ==================== part2.cpp
=====================
#include "part2.h" void bubble_sort (list<int> &l) { } void bubble_sort (vector<int> &v) { }
Explanation / Answer
unsigned int ELEMENT_COUNT = 4000;
const unsigned int MAXVALUE = 99999;
void bubble_sort_list (list & l)
{
bool swapped;
if (l.size() <= 1)
return;
do
{
swapped = false;
// Add code here
} while (swapped);
}
void bubble_sort_vector (vector & v)
{
bool swapped;
if (v.size() <= 1)
return;
do
{
swapped = false;
for (unsigned int i=1;i<v.size();i++)
{
if (v[i-1] > v[i])
{
unsigned int temp;
swapped = true;
temp = v[i-1];
v[i-1] = v[i];
v[i] = temp;
}
}
} while (swapped);
}
void fill_list (list &l)
{
for (unsigned int i=0;i<ELEMENT_COUNT;i++)
{
l.push_back( (unsigned int)rand()%MAXVALUE);
}
}
void fill_vector (vector &v)
{
for (unsigned int i=0;i<ELEMENT_COUNT;i++)
{
v.push_back( (unsigned int)rand()%MAXVALUE);
}
}
bool isAscending (list &l)
{
if (l.size() <= 1)
return true;
list::iterator i = l.begin();
list::iterator j = ++(l.begin());
while (j != l.end())
{
if (*i > *j)
return false;
++j;
++i;
}
return true;
}
bool isAscending (vector &v)
{
if (v.size() <= 1)
return true;
for (unsigned int i = 1;i <v.size() - 1 ; ++i)
{
if (v[i-1] > v[i])
return false;
}
return true;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.