#include #include using namespace std; void MergeSort(string & s); int main() { string phrase; cout << "Enter a string " ; getline (cin, phrase); cout << endl; cout << "Sorting \"" << phrase << '"' << endl; MergeSort(phrase); cout << "That becomes \"" << phrase << '"' << endl; return 0; } void MergeSort(string & s) { size_t pos; // substrings string a,b; // for merging size_t aPos = 0, bPos = 0; // base case, nothing to sort. if (s.size() < 2) { return; } //split into two substrings. pos = s.size()/2; a = s.substr(0,pos); b = s.substr(pos, string::npos); // sort the two substrings MergeSort(a); MergeSort(b); // merge the results. // initialize the return string to empty. s = ""; // merge the two lists. while (aPos < a.size() and bPos < b.size() ) { if (a[aPos] < b[bPos]) { s += a[aPos]; aPos++; } else { s += b[bPos]; bPos++; } } // add the part left over in the remaining substring if (aPos < a.size()) { s += a.substr(aPos, string::npos); } else { s += b.substr(bPos, string::npos); } return; }