106k views
2 votes
Given two Strings, s1 and s2, write a Java program that determines if s2 is an anagram of s1 using Bubble sort. If it is, print s1 in alphabetical order. If it is not, print s1 and s2 in alphabetical order.

Sample Input 1
anagram
nagaram
Sample Output 1
aaagmnr
Sample Input 2
cat
mat
Sample Output 2
act
amt

1 Answer

6 votes

Final answer:

The provided Java program uses Bubble sort to determine if s2 is an anagram of s1. It sorts both strings and compares them, printing the sorted s1 if they're anagrams, or both sorted strings if they're not.

Step-by-step explanation:

To determine if one string is an anagram of another in Java, we can use Bubble sort to sort both strings and then compare them. Below is a Java program that checks if s2 is an anagram of s1 and prints them in alphabetical order accordingly.

public class AnagramCheck {
public static void main(String[] args) {
String s1 = "anagram";
String s2 = "nagaram";
if (isAnagram(s1, s2)) {
System.out.println(sortString(s1));
} else {
System.out.println(sortString(s1) + " " + sortString(s2));
}
}

public static boolean isAnagram(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;
}
return sortString(s1).equals(sortString(s2));
}

public static String sortString(String s) {
char[] characters = s.toCharArray();
for (int i = 0; i < characters.length; i++) {
for (int j = 0; j < characters.length - i - 1; j++) {
if (characters[j] > characters[j + 1]) {
char temp = characters[j];
characters[j] = characters[j + 1];
characters[j + 1] = temp;
}
}
}
return new String(characters);
}
}

In this program, the sortString method sorts a string using Bubble sort, and the isAnagram method compares the sorted strings. If they are equal, it means s2 is an anagram of s1. Otherwise, it prints both strings sorted.

User Lanny
by
8.1k points