...

/

Merging Strings in Alphabetic Order

Merging Strings in Alphabetic Order

This lesson will teach you how to merge two already sorted strings using recursion so that the resulting string is also sorted.

What do we mean by merging alphabetically?

When given two strings that are in alphabetic order, we can combine them to create a string that is both sorted alphabetically and the combination of those two strings.

To better understand, look see the illustration below:

Implementing the Code

The code below shows how to merge alphabetically using recursion. First, let’s examine the code, and 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
class ExampleClass {
private static String alphabeticMerge(String one, String two) {
if (one == null || one.equals("")) {
return two==null? one:two;
}
else if (two == null || two.equals("")) {
return one;
}
else if (two.charAt(0) > one.charAt(0)) {
return one.charAt(0) + alphabeticMerge(one.substring(1, one.length()), two);
}
else {
return two.charAt(0) + alphabeticMerge(one, two.substring(1, two.length()));
}
}
public static void main( String args[] ) {
String one = "adz";
String two = "bfx";
String answer = alphabeticMerge(one, two);
System.out.println(answer);
}
}

Understanding the Code

The recursive code can be ...