Bubble Sort for Strings

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <iomanip>

using namespace std;

class Property
{		//Private attribute 
	private:		
		string name;
	
	public:
		void set_details(string propname)
		{
			name = propname;
		}
		
		//Getter 	
		string get_name(){return name;}
		
};

//Derived Class
class Details : public Property
{

	public:
	Details(){}
	Details(string propname)
		{
			set_details(propname);
		}
		
	void bubbleSortName(int size)
	{
		Details data[10];
		string temp;
		// Sorting strings using bubble sort
    for(int k = 0; k< size-1; k++) {
        // (size-k-1) is for ignoring comparisons of elements which have already been compared in earlier iterations

        for(int i = 0; i < size-k-1; i++) {
            if(data[ i ].get_name() > data[ i+1].get_name() ) {
                // here swapping of positions is being done.
                temp = data[ i ].get_name();
                data[ i ].get_name() = data[ i+1 ].get_name();
                data[ i + 1].get_name() = temp;
            	}
        	}
    	}
	}

};

void propertyNameAssortment(Details data[10], int count)
{
	Details myDetails;
	
	myDetails.bubbleSortName(5);

	if(count != 0)
	{
		cout <<"\n=================="<<endl
			 <<"\n\t\t\t Viewing All Properties"<<endl
			 <<"\n================="<<endl
			 <<"\n|   No   |   Property Type   |"
			 <<"\n================="<<endl;
			 
			 for(int i = 0; i< count; i++)
			{
				cout << setw(8) << i+1
					 << setw(15) << data[i].get_name() << "\t\t"
					 << endl;
			}

	}
	else
	{
		cout << endl << endl << endl
			 << "\t\t\t There is no property in the system";
	}
}

int main()
{
	Details data[10];
	
	//Preset data
	Details data1("Terrace");
	Details data2("Apartment");
	Details data3("Bungalow");
	Details data4("Factory");
	Details data5("Mall");
	
	//Replace location for each preset data
	data[0] = data1;
	data[1] = data2;
	data[2] = data3;
	data[3] = data4;
	data[4] = data5;
	
	propertyNameAssortment(data,5);
}
Last edited on
> myDetails.bubbleSortName(5);
Maybe sort the parameter, rather than some local parameter containing nothing.

Your sort function has the same problem - sorting a local array rather than the real data.
Lets look at your "bubble":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
nomnomu wrote:
I wanted to sort the data in main... Is there any way to relate my bubble to the data in main?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <iomanip>
#include <string>
#include <algorithm>
using namespace std;

class Property
{
   private:
      string name;
	
   public:
      Property(){}
      void set_name( const string &propname ) { name = propname; }
      string get_name(){ return name; }
};

void propertyList( Property data[], int num )
{
   if ( num )
   {
      cout <<"\n==================\n"
           <<"\nViewing All Properties\n"
           <<"\n==================\n"
           <<"\n|   No   |   Property Type   |"
           <<"\n==================\n";
 
      for ( int i = 0; i < num; i++ )
      {
         cout << setw(8) << i + 1
              << setw(15) << data[i].get_name() << '\n';
      }
   }
}

int main()
{
   Property data[10];
   data[0].set_name( "Terrace" );
   data[1].set_name( "Apartment" );
   data[2].set_name( "Bungalow" );
   data[3].set_name( "Factory" );
   data[4].set_name( "Mall" );

   sort( data, data + 5, []( Property a, Property b ){ return a.get_name() < b.get_name(); } );
   propertyList( data, 5 );
}


==================

Viewing All Properties

==================

|   No   |   Property Type   |
==================
       1      Apartment
       2       Bungalow
       3        Factory
       4           Mall
       5        Terrace





If you are required to do your own bubble sort and swapping then (without optimising for "already sorted"):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

class Property
{
   private:
      string name;
	
   public:
      Property(){}
      void set_name( const string &propname ) { name = propname; }
      string get_name(){ return name; }
};

void propertyList( Property data[], int num )
{
   if ( num )
   {
      cout <<"\n==================\n"
           <<"Viewing All Properties"
           <<"\n==================\n"
           <<"|   No   |   Property Type   |"
           <<"\n==================\n";
 
      for ( int i = 0; i < num; i++ )
      {
         cout << setw(8) << i + 1
              << setw(15) << data[i].get_name() << '\n';
      }
   }
}


void bubbleSortName( Property data[], int num )
{
   for ( int k = 0; k < num - 1; k++ )
   {
      for ( int i = 0; i < num - 1 - k; i++ )
      {
         if ( data[i].get_name() > data[i+1].get_name() )
         {
            Property temp = data[i];
            data[i] = data[i+1];
            data[i+1] = temp;
         }
      }
   }
}



int main()
{
   Property data[10];
   data[0].set_name( "Terrace" );
   data[1].set_name( "Apartment" );
   data[2].set_name( "Bungalow" );
   data[3].set_name( "Factory" );
   data[4].set_name( "Mall" );

   bubbleSortName( data, 5 );
   propertyList( data, 5 );
}
Last edited on
If you are required to do your own bubble sort and swapping then (without optimising for "already sorted"):

yes... thank you so much, this helps a lot^^
@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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <iostream>
#include <iomanip>

using namespace std;

class Property
{
private:
    string m_name{"???"};

public:
    Property(){}
    Property(std::string name){m_name = name;}

    string get_name(){return m_name;}

    bool operator> (Property &rhs)
    {
        if( this -> m_name > rhs.m_name)
            return true;
        else
            return false;
    }

    bool operator< (Property &rhs)
    {
        if( this -> m_name < rhs.m_name)
            return true;
        else
            return false;
    }
};

class Portfolio
{
public:
    Portfolio(){}

    void bubbleSortAscending(Property data[], size_t count)
    {
        Property temp{};
        for (int i = 0; i < count - 1; i++)
        {
            for (int j = 0; j < count - i - 1; j++)
            {
                if (data[j] > data[j+1])
                {
                    temp = data[j+1];
                    data[j+1] = data[j];
                    data[j] = temp;
                }
            }
        }
    }

    void bubbleSortDescending(Property data[], size_t count)
    {
        Property temp{};
        for (int i = 0; i < count - 1; i++)
        {
            for (int j = 0; j < count - i - 1; j++)
            {
                if (data[j] < data[j+1])
                {
                    temp = data[j+1];
                    data[j+1] = data[j];
                    data[j] = temp;
                }
            }
        }
    }

    void printPortfolio(Property data[], size_t count)
    {

        if(count != 0)
        {
            cout
            <<  '\n'
            << "=================================\n"
            << "     Viewing All Properties      \n"
            << "=================================\n"
            << "No      Property Type\n"
            << "=================================\n";

            for(int i = 0; i < count; i++)
            {
                cout
                << setw(8) << std::left << i + 1
                << setw(15) << std::left << data[i].get_name()
                << '\n';
            }
        }
        else
        {
            cout << endl << endl << endl
            << "          There is no property in the system\n";
        }
    }
};

int main()
{
    Property data[]
    {
        Property("Terrace"), Property("Apartment"),
        Property("Bungalow"), Property("Factory"),
        Property("Mall"), Property("Zoo")
    };

    size_t size = sizeof(data)/sizeof(Property);

    Portfolio prtfolio;

    prtfolio.bubbleSortAscending(data, size);
    prtfolio.printPortfolio(data, size);

    prtfolio.bubbleSortDescending(data, size);
    prtfolio.printPortfolio(data, size);
}



=================================
     Viewing All Properties      
=================================
No      Property Type
=================================
1       Apartment      
2       Bungalow       
3       Factory        
4       Mall           
5       Terrace        
6       Zoo            

=================================
     Viewing All Properties      
=================================
No      Property Type
=================================
1       Zoo            
2       Terrace        
3       Mall           
4       Factory        
5       Bungalow       
6       Apartment      
Program ended with exit code: 0
Perhaps even:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <iomanip>
#include <string>
#include <utility>
#include <iterator>

class Property {
public:
	Property() {}
	Property(const std::string& p) : name(p) {}
	Property(const char* p) : name(p) {}

	void set_name(const std::string& propname) { name = propname; }
	std::string get_name() const { return name; }

	bool operator> (const Property& rhs) const { return name > rhs.name; }
	bool operator< (const Property& rhs) const { return name < rhs.name; }

private:
	std::string name;
};

void propertyList(const Property data[], size_t num)
{
	if (num > 0) {
		std::cout
			<< '\n'
			<< "=================================\n"
			<< "     Viewing All Properties      \n"
			<< "=================================\n"
			<< "No      Property Type\n"
			<< "=================================\n";

		for (size_t i = 0; i < num; ++i)
			std::cout
				<< std::setw(8) << std::left << i + 1
				<< std::setw(15) << std::left << data[i].get_name()
				<< '\n';
	} else
		std::cout << "\n\n\n          There are no properties in the system\n";
}

void bubbleSortNameAsc(Property data[], size_t num)
{
	for (size_t k = 0; k < num - 1; ++k)
		for (size_t i = 0; i < num - 1 - k; ++i)
			if (data[i] > data[i + 1])
				std::swap(data[i], data[i + 1]);
}

void bubbleSortNameDesc(Property data[], size_t num)
{
	for (size_t k = 0; k < num - 1; ++k)
		for (size_t i = 0; i < num - 1 - k; ++i)
			if (data[i] < data[i + 1])
				std::swap(data[i], data[i + 1]);
}

int main()
{
	Property data[] {"Terrace", "Apartment", "Bungalow", "Factory", "Mall"};

	bubbleSortNameAsc(data, std::size(data));
	propertyList(data, std::size(data));

	bubbleSortNameDesc(data, std::size(data));
	propertyList(data, std::size(data));
}

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.

http://www.cplusplus.com/doc/tutorial/functions/
http://www.cplusplus.com/doc/tutorial/arrays/
Or sort the array in main() ...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main()
{
    Property data[]
    {
        Property("Terrace"), Property("Apartment"),
        Property("Bungalow"), Property("Factory"),
        Property("Mall"), Property("Zoo")
    };

    size_t size = sizeof(data)/sizeof(Property);

    Property temp{};
    for (int i = 0; i < size - 1; i++)
    {
        for (int j = 0; j < size - i - 1; j++)
        {
            if (data[j] > data[j+1])
            {
                temp = data[j+1];
                data[j+1] = data[j];
                data[j] = temp;
            }
        }
    }

// etc etc etc
    

}
Registered users can post here. Sign in or register to post.