...

/

Merging Strings in Alphabetic Order

Merging Strings in Alphabetic Order

This lesson will teach you how to merge two already sorted strings so that the resultant string is also sorted

What do we mean by merging alphabetically?

Given two strings that are already in alphabetic order, we can combine them to create a string that is sorted alphabetically and is a combination of the two strings given. For a better understanding, look at the illustration below:

Implementing the Code

The code below shows how to do this with recursion. First, let’s see the code, then we can go on to its explanation.

Try the code by changing the values of one and two to see how it works with other strings.

Press + to interact
#include <iostream>
#include <string>
using namespace std;
string alphabeticMerge(string one, string two) {
if(one[0]=='\0')
{
if(two[0]=='\0'){
return one;
}
return two;
}
else if (two[0]=='\0')
return one;
else if(one[0] > two[0])
return two[0] + alphabeticMerge(one,two.substr(1));
return one[0] + alphabeticMerge(one.substr(1), two);
}
int main(){
string one="adefz";
string two="bcfgy";
string answer=alphabeticMerge(one,two);
cout<<answer<<endl;
}

Understanding the Code

Recursive code can be broken down into two parts. The first is the ...