I was asked to write a program that sorts three strings alphabetically using only if-else (no sorting algorithms, usage of arrays whatsover). I'm fairly new to C++ programming but I've come up with this program and would like to know if there's any way to make this more efficient while only using if-else? Any help or suggestions would be appreciated. Thank you!
#include <iostream> using namespace std; int main() { string word1, word2, word3; string temp; cout << "Enter three words separated by a space: "; cin >> word1 >> word2 >> word3; if (word1 > word2 && word1 > word3 && word3 > word2) { temp = word1; word1 = word2; word2 = word3; word3 = temp; } else if (word1 > word2 && word1 > word3 && word2 > word3) { temp = word1; word1 = word3; word3 = temp; } else if (word2 > word1 && word2 > word3 && word1 > word3) { temp = word2; word1 = word3; word2 = word1; word3 = temp; } else if (word2 > word1 && word2 > word3 && word3 > word1) { temp = word2; word2 = word3; word3 = temp; } else if (word3 > word1 && word3 > word2 && word1 > word2) { temp = word1; word1 = word2; word2 = temp; } cout << "The correct sort is " << word1 << ", " << word2 << ", " << word3 << endl; return 0; }
compare
method of that class which performs a lexicographical compare on the strings.\$\endgroup\$