Hi so I wrote this code for my assignment and was confused as to why my bubble sort isn't working. Please tell me why isn't my bubble sort working and how do I fix it?
void Details::bubbleSortName( int size )
{
Details data[10]; // Array of 10 unknown Details
string temp;
for ( int k = 0; k< size-1; k++ ) {
for ( int i = 0; i < size-k-1; i++ ) {
if ( data[ i ].get_name() > data[ i+1].get_name() ) {
temp = data[ i ].get_name();
data[ i ].get_name() = data[ i+1 ].get_name(); // error
data[ i + 1].get_name() = temp;
}
}
}
}
On line 3 you declare an array with name "data". Your loops operate on that array. That array has nothing to do with any other array; it is totally unrelated to "data" in main().
On line 9 you try to assign to unnamed temporary string that was returned by data[ i ].get_name().
If you want to change name, then you should use the set_details().
However, ... lets say that John and Jill stand in queue. You want to have them in alphabetical order.
A normal person would tell Jill to move forward, to front of John.
You don't do that. You (attempt) rename the boy "Jill" and the girl "John". Is that what you really want?
You send an array data[] to propertyNameAssortment() ... then do nothing with it.
Instead you create a NEW object myDetails ... with nothing in it ... but decide to sort that!
Within bubbleSortName() ... you create a NEW array called data ... again with nothing in it ... and proceed to try to sort that (incorrectly, but that is the least of your worries).
In the first instance, just use std::sort with a predicate to sort by name. If you need your own sort then it shouldn't be a member variable of the object you are trying to sort. I'd make it a stand-alone function.
Your whole class/derived-class arrangement is a bit weird.
I wanted to sort the data in main... Is there any way to relate my bubble to the data in main? Sorry if it looks weird because I just took out any related code with it.
@OP
Definitely hard to see where inheritance is useful.
operator<, and > overloads might be useful.
I changed the class names to sound meaningful, to me at least.
I wanted to sort the data in main... Is there any way to relate my bubble to the data in main?
"Relate function to data"
We usually say: "Call function with data as argument."
1 2 3 4 5 6 7
void func( T parameter ) {
// do operations on parameter
}
// used:
T argument;
func( argument );
Function can take parameters by value or by reference.
A by value parameter is just a copy of caller's argument's value.
A by reference parameter is a reference to caller's argument. Can change caller's variable.
Plain arrays are passed by value, but the twist is that the array is not passed nor copied; function gets only a pointer to array. Hence function can modify caller's array.