Hello everyone, I am familiar with a normal bubble sort when dealing with an array of number but I am unsure as how to implement a sort when I have an array that is filled with classes which hold multiple values.
I need to make a bubble sort that reaches into an array called Tree[100] which has in each storage location a class called Christmas Tree which have the values Species, Height, trunkDiameter, and costPerFoot. The sort will need to sort the different trees by species (which is a string) and then by costPerFoot (a double).
Regular bubble sort: - void bubblesort (int a[], int n) // n = SIZE;
-
{
-
bool sorted = false;
-
for (int i = 0; i < n-1 && !sorted; i++)
-
{
-
sorted = true;
-
for (int j = 0; j < (n-1-i); j++)
-
{
-
if (a[j] > a[j+1])
-
{
-
swap (a[j], a[j+1]);
-
sorted = false;
-
}
-
}
-
}
-
}
Any ideas?
12 8609
I had an idea. I have a function called getSpecies() and getCost() which simply returns the values found in whatever array area your in. Could I... - void bubblesort (char a[], int n) // n = SIZE;
-
{
-
bool sorted = false;
-
for (int i = 0; i < n-1 && !sorted; i++)
-
{
-
sorted = true;
-
for (int j = 0; j < (n-1-i); j++)
-
{
-
if ( a[j].getSpecies() > a[j+1].getSpecies() )
-
{
-
swap (a[j], a[j+1]);
-
sorted = false;
-
}
-
}
-
}
-
}
-
-
That idea will work...if you pass an array of this class/struct. Right now you are passing in a character array, then trying to use a class function on it. Characters are not classes. You will want to pass a Tree[] to your function and sort that.
Even better, overload the < and > operators for Tree. You can compare names first - if the names are the same, you can compare some other attribute.
This will allow you to write a generalized bubblesort using templates: - template <class Comparable>
-
void bubble_sort(Comparable[] array, int size);
That idea will work...if you pass an array of this class/struct. Right now you are passing in a character array, then trying to use a class function on it. Characters are not classes. You will want to pass a Tree[] to your function and sort that.
Even better, overload the < and > operators for Tree. You can compare names first - if the names are the same, you can compare some other attribute.
This will allow you to write a generalized bubblesort using templates: - template <class Comparable>
-
void bubble_sort(Comparable[] array, int size);
I havnt worked with templates so im a bit confused. Would it look something like this?
template <class Tree>
void bubble_sort(Tree[], int size);
Im afraid that may be too difficult for my experience with C++. Anyway this is what im up to: - void bubblesort (??? a[], int n); // Prototype
-
-
void bubblesort (Tree[], int n) // n = SIZE;
-
{
-
bool sorted = false;
-
for (int i = 0; i < n-1 && !sorted; i++)
-
{
-
sorted = true;
-
for (int j = 0; j < (n-1-i); j++)
-
{
-
if ( a[j].getSpecies() > a[j+1].getSpecies() )
-
{
-
swap (a[j], a[j+1]);
-
sorted = false;
-
}
-
}
-
}
-
}
Is there a data type or something I could do in order for it to work?
Im afraid that may be too difficult for my experience with C++. Anyway this is what im up to: - void bubblesort (??? a[], int n); // Prototype
-
-
void bubblesort (Tree[], int n) // n = SIZE;
-
{
-
bool sorted = false;
-
for (int i = 0; i < n-1 && !sorted; i++)
-
{
-
sorted = true;
-
for (int j = 0; j < (n-1-i); j++)
-
{
-
if ( a[j].getSpecies() > a[j+1].getSpecies() )
-
{
-
swap (a[j], a[j+1]);
-
sorted = false;
-
}
-
}
-
}
-
}
Is there a data type or something I could do in order for it to work?
We're closer here. First, I'll explain about templates.
Templates basically allow you to write a generalized function. So, if I had a function: - template <class T>
-
T addTwo(T& objectOne, T& objectTwo) {
-
return objectOne + objectTwo;
-
}
I can now call addTwo on any class or type that the + operator makes sense. So, for instance, I could call it in this way: - int x = addTwo<int>(5, 20);
Note the <int> - this tells the function what class or type I am filling in for the template. So, by putting the <int> there, I've effectively changed this function to - int addTwo(int& objectOne, int& objectTwo) {
-
return objectOne + objectTwo;
-
}
But that change only lasts for that one call. I can still later say - double y = addTwo<double>(3.5, 12.02);
and it will work. I can even add classes that have a + operator - for instance, if I defined a Vector class, and gave it a + operator, I could say - Vector resultant = addTwo<Vector>(firstVec, secondVec);
All three of these examples work.
Now, in your case, you are writing a bubblesort function. When sorting, generally you only need to know if an object is less than or greater than another object. You don't care what type the objects are, as long as you can compare them - they could be numbers, they could be Trees, they could be Apple Pies, they could be anything, as long as you can compare them. You put this into code by using a template, and when it comes time to compare one object to another, use the '<' operator. You can assume that whatever object you are sorting has the '<' operator, because it makes no sense to sort an object that cannot be sorted.
Now that you are using templates, you can write a generic bubble sort function. When writing it, forget the fact that you are working with Trees. Just think about sorting some general object - it's common to think about sorting integers, as it's easy to visualize and see whether integer A is larger than or smaller than integer B. Once you have your bubblesort function working, then you have one more thing to worry about - does your Tree class overload the '<' operator?
In order to do so, you need to provide the following function in your Tree class: - bool operator<(Tree& rightHandSide) const;
The body of this function will determine if the current tree is less than the rightHandSide tree, and if so, return true. Otherwise, it must return false. This is where you will compare the Tree's species type and anything else you wanted to sort by.
Im so sorry but some of that I dont understand, im only in Intro to C++ and we are at the final stage of our learning for the semester so vectors and the like I havnt gotton to yet. I did however find a way that it will work but I encounter a problem that maybe someone can help me with. The point of this program is to open up a file with an unknown number of Tree[]s in it then read the lines and put the correct data into the correct part in the array in the class.
Example data
Douglas Fir
3.38
4.38
12.29
Ponderous Pine
11.37
5.45
11.5
So I have a for loop that I thought would read each part and put it into its correct area: - for (int i = 0; inData; i++)
-
{
-
inData >> s;
-
-
inData.ignore(MAX, '\t');
-
inData >> h;
-
-
inData.ignore(MAX, '\t');
-
inData >> tD;
-
-
inData.ignore(MAX, '\t');
-
inData >> cPF;
-
-
inData.ignore(MAX, '\t');
-
-
Tree[i].setSpecies(s);
-
Tree[i].setHeight(h);
-
Tree[i].setTrunkDiameter(tD);
-
Tree[i].setCostPerFoot(cPF);
-
-
count++;
-
}
But whenever I check my program it only gives me the output of my constructor function so its as if the programs cursor is not in the right location or not doing something right. This is last problem I can find so help is appreciated!
In order to do so, you need to provide the following function in your Tree class:
Code: ( cpp )
bool operator<(Tree& rightHandSide) const;
There is also the option of writing the operator< as a regular global function: -
bool operator<(Tree& lefthandside, Tree& rightHandSide);
-
In your sort you should, be able to:
Ok, ive made some progress and im down to my last two problems. First off, after ive opened up the file and sorted my trees by Species, I want to sort them ALSO by cost. but I am unsure of how to do that.
Current bubblesort for species: - void bubblesort ( ChristmasTree a[],int n) // n = SIZE;
-
{
-
bool sorted = false;
-
for (int i = 0; i < n-1 && !sorted; i++)
-
{
-
sorted = true;
-
for (int j = 0; j < (n-1-i); j++)
-
{
-
if ( a[j].getSpecies() > a[j+1].getSpecies() )
-
{
-
swap (a[j], a[j+1]);
-
sorted = false;
-
}
-
-
-
-
}
-
}
-
}
The last problem is with outputting the trees to the screen. I have a for loop that outputs them like so: -
for (int i = 0; i < count - 1; i++)
-
{
-
cout << fixed << setprecision(2)
-
<< Tree[i].getSpecies() << endl;
-
cout << Tree[i].getHeight() << endl;
-
cout << Tree[i].calculateCost() << endl;
-
-
total += Tree[i].calculateCost();
-
}
-
-
cout << "There are " << count << " trees listed." << endl;
-
cout << "The average price of a tree is " << total/count << endl;
But in the actual output I get my constructor listed like 20 times before it starts listing the other trees. whats up with that?
Ex. - Blue Spruce
-
8.36
-
188.10
-
Blue Spruce
-
9.98
-
224.55
-
Douglas Fir
-
3.38
-
41.41
-
Douglas Fir
-
4.88
-
59.78
-
Douglas Fir
-
8.59
-
105.23
- Fraser Fir
-
6.00
-
77.70
-
Fraser Fir
-
6.00
-
77.70
-
Fraser Fir
-
6.00
-
77.70
-
Fraser Fir
-
6.00
-
77.70
-
Fraser Fir
-
6.00
-
77.70
-
Fraser Fir
-
6.00
-
77.70
-
-
Ponderosa Pine
-
11.37
-
130.75
-
Ponderosa Pine
-
12.83
-
147.54
-
Ponderosa Pine
-
11.09
-
127.53
-
Ponderosa Pine
-
5.58
-
64.17
-
Ponderosa Pine
-
6.81
-
78.31
-
Ponderosa Pine
-
4.12
-
47.38
Do you want to sort separately i.e. have two separate functions - one that sorts by cost, the other that sorts by species? This is fairly simple - you can copy and paste your code, and change getSpecies to getCost.
Or do you want them sorted by species, and each subset of species sorted by cost? To do this, in your sort, consider when you would need to sort by cost - only when the species is the same, right? Then you can add another possibility to your if...statement in the inner loop.
Do you want to sort separately i.e. have two separate functions - one that sorts by cost, the other that sorts by species? This is fairly simple - you can copy and paste your code, and change getSpecies to getCost.
Or do you want them sorted by species, and each subset of species sorted by cost? To do this, in your sort, consider when you would need to sort by cost - only when the species is the same, right? Then you can add another possibility to your if...statement in the inner loop.
When you say add another possiblity do you mean add something like:
if(a[j].getSpecies() > a[j+1].getSpecies() || a[j].calculateCost() > a[j+1].calculateCost())
or add another if statement?
I mean you should either say: - if (a[j].species > a[j+1].species OR (a[j] and a[j+1] have the same species AND a[j].cost > a[j+1].cost)) {
-
// swap...blah blah blah.
-
}
or you should say - if (a[j].species > a[j+1].species) {
-
// swap...blah blah blah
-
} else if (a[j] and a[j+1] have the same species AND a[j].cost > a[j+1].cost) {
-
// swap...blah blah blah
-
}
You might consider a comparator function. Here you write a function that does the correct comparison and pass the address of the function to the bubble sort as an argument.
You would write a function that takes two Tree& arguments and you pass a pointer to this function to the bubble sort as a function pointer. Inside the sort you call the function by using the function pointer. The sort will then produce the sequence based on that call.
Assume you have written: -
bool Seq1(Tree& left, Tree& right); //sorts ascending
-
bool Seq2(Tree& left, Three& right); //sorts descending
-
bool Seq3(Tree&left, Tree& right); //sorts by SPECIES ascending
-
etc...
-
Your sort: -
void bubblesort (int a[], int n, bool (*Compare)(Tree&, Tree&))
-
{
-
if (Compare(a[i], a[i+1])
-
{
-
//a[i] is "less" than a[i+1]
-
}
-
}
-
Then you can call the sort to get three different sequences: -
bubblesort(a, 100, Seq1);
-
bubblesort(a, 100, Seq2);
-
bubblesort(a, 100, Seq3);
-
To use your operator< you could: -
bool Seq4(Tree& left, Tree& right)
-
{
-
return left < right:
-
}
-
and to sort in the reverse sequence (>=): -
bool Seq4(Tree& left, Tree& right)
-
{
-
if (left < right)
-
{
-
return false;
-
}
-
return true;
-
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Chris |
last post by:
I have a bubble sort for a 2-dimensional array that sorts a
string,number pair based on the number. The code for the sort is as
follows:
Private Sub SortArray(ByRef roundarray(,) As String)...
|
by: Protoman |
last post by:
Why doesn't my double bubble sort algorithm sort; it just spits the
numbers out, int the exact same order that I inputted them.
Code:
void swap(int& i,int& j)
{
i^=j;
j^=i;
i^=j;
|
by: Slowjam |
last post by:
How do I correct the program below to search all the anagrams in a given file.
First, for each word, build another word (its key) with all its letters sorted. For instance, build "dorw" for...
|
by: kuchma2000 |
last post by:
Hi.
I have a C program (see code below) which I need to urgrade. All I need to do is:
a. Extract the temps for the City #1 and store in a one dimensional array, display the array.
b. Sort the one...
|
by: Acolyte |
last post by:
Hey, I'm working on a project that involves sorting a two-dimensional array of integers using bubble sort. I've got it semi-working, my only issue is that it seems to be 'losing' values, I'm assuming...
|
by: Sheepman |
last post by:
I've been working on this since Wednesday and am at a total loss. I need to bubble sort a randomly generated list of numbers. I got the numbers in about 15 minutes. The remainder of the 3 days have...
|
by: xtheendx |
last post by:
I am writing a gradbook type program. It first allows the user to enter the number of students they want to enter. then allows them to enter the first name, last name, and grade of each student. The...
|
by: mahdiahmadirad |
last post by:
Hi dears!
I wrote a simple bubble sort algorithm. it works properly when we compare full arrays but i want to sort a 2d array according to a specific part of array. it has some problem to swapping...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |