Hello everyone,
I'm having some trouble with the code for merge sort. I get what is it but the code doesn't seem to work. Here is my code:
Any ideas?
I'm having some trouble with the code for merge sort. I get what is it but the code doesn't seem to work. Here is my code:
Code:
////.h #include <iostream> #include <string> using namespace std; string merge(string,string); string mergeSort(string); string rest(int,int,string); string rest(int from,int to,string phrase){ string temp; for(int i=from;i<=to;i++){ temp[i-1]=phrase[i]; } return temp; } string merge(string left,string right){ string result; * * while (left.length() > 0 || right.length() > 0){ * * * * if (left.length() > 0 && right.length() > 0){ if (left[0] <= right[0]){ * * * * * * * * result+=left[0]; * * * * * * * * left= rest(1,left.length(),left); } if(left[0]>right[0]) * * { result+=right[0]; right= rest(1,right.length(),right); } if (left.length() > 0){ result+= left[0]; left= rest(1,left.length(),left); } if (right.length() > 0){ * * result+=right[0]; right= rest(1,right.length(),right); } } } return result; } string mergeSort(string a){ if(a.length()<=1) return a; string left,right,result; int middle=(a.length())/2; for(int i=0;i<a.length();i++){ if(i<middle) * left+=a[i]; else* if(i>=middle) right+=a[i]; } left = mergeSort(left); * * right = mergeSort(right); * * result = merge(left, right); * * return result+left; } ////.cpp #include "mergeSort.h" using namespace std; int main () { * * string a,b; int again=1; while(again==1){ * * cout<<"Enter string to sort: "; * * cin>>a; cout<<"Before the sort: "<<a<<endl; cout<<"After sort: "; cout<<mergeSort(a)<<endl; * * cout<<"1-Again* 2-Close: "; cin>>again; } * * return 0; }
Comment