I'm trying to figure out how to use a bubble sort in a array of names. since the names are type string, I can't figure out how to alter the bubble sort to do this.

all the examples I find online deal with numbers instead of strings.

So how do I sort last names alphabetically using the bubble sort?

Any help much welcomed

Recommended Answers

All 4 Replies

See http://www.cplusplus.com/reference/clibrary/cstring/strcmp/ for strcmp. You need to include <cstring> and your strings you are comparing need to be cstrings (so like the char * variety). You can get strings of this format from your C++ strings by using the c_str() method of any string object mystring.c_str() .

EDIT: You can also use the < , > , >=,<= operators with the C++ strings http://www.cplusplus.com/reference/string/operators/

See http://www.cplusplus.com/reference/clibrary/cstring/strcmp/ for strcmp. You need to include <cstring> and your strings you are comparing need to be cstrings (so like the char * variety). You can get strings of this format from your C++ strings by using the c_str() method of any string object mystring.c_str() .

we havent done strcmp in class yet.
:(

See my edit above. If not you're going to have to go through the strings character by character until they don't match, decide which one is greater, and then swap the one that's greater towards the end of the array.

If you std::strings, then you could just compare them as if you would compare it with numbers.

int x = 4;
int y = 4;
bool b = x == y;

std::string str = "abc";
std::string str2 = "abc";
bool b2 = str == str2;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.