algorithm - C++: Implementing merge sort from scratch -
i trying test self , wanted write mergesort, without looking code online, , in time period. stuck @ point cannot understand doing wrong, since merge sort, as remember, divide strings point string 1 character , later on merge them together. code i've written below tries exact thing. wondering whether got concept wrong, or my implementation?
string merge(string str1, string str2) { string final = ""; int = 0, j = 0; bool fromstr1 = false; while(true) { if(str1[i] < str2[j]) { final += str1[i]; i++; if(i == str1.size()) { break; } } else { final += str2[j]; j++; if(j == str2.size()) { break; fromstr1 = true; } } } if(fromstr1) { for(int t = i; t < str1.size(); t++) { final += str1[t]; } } else { for(int t = j; t < str2.size(); t++) { final += str2[t]; } } return final; } string mergesort(string str1, int start, int end) { if(end - start == 1) return str1; else { int pivot = (end - start) / 2; string newstr1 = mergesort(str1, start, pivot); string newstr2 = mergesort(str1, pivot + 1, end); return merge(newstr1, newstr2); } }
note changes:
#include <iostream> #include <string> using namespace std; string merge(string str1, string str2) { string final = ""; int = 0, j = 0; bool fromstr1 = false; while (true) { if (i >= (int)str1.size()) { break; } if (j >= (int)str2.size()) { fromstr1 = true; // changed order of break! break; } if (str1[i] < str2[j]) { final += str1[i]; i++; } else { final += str2[j]; j++; } } if (fromstr1) { (int t = i; t < (int)str1.size(); t++) { final += str1[t]; } } else { for(int t = j; t < (int)str2.size(); t++) { final += str2[t]; } } return final; } string mergesort(string str1) { int len = str1.size(); if (len <= 1) return str1; else { string newstr1 = mergesort(str1.substr(0, len / 2)); string newstr2 = mergesort(str1.substr(len / 2, len - len / 2)); return merge(newstr1, newstr2); } } int main() { cout << '"' << mergesort("") << '"' << endl; cout << '"' << mergesort("a") << '"' << endl; cout << '"' << mergesort("ba") << '"' << endl; cout << '"' << mergesort("132") << '"' << endl; cout << '"' << mergesort("4321") << '"' << endl; cout << '"' << mergesort("54321") << '"' << endl; return 0; }
output (ideone):
"" "a" "ab" "123" "1234" "12345"
Comments
Post a Comment