I am practicing java and some algorithms so I wanted to create a program to see if 2 words are anagrams of each other. My method was to use a quicksort to sort the words and then see if they matched. I tested me quicksort
function and it seemed to work. Perhaps my anagram function is wrong? I tested my code against "tac"
and "cat"
and I am getting false
.
Could someone take a look at my code and see where I went wrong?
my code:
public static boolean anagram(String s, String t) {
int lenS = s.length();
int lenT = t.length();
if (lenS != lenT) {
return false;
}
else if (quicksort(s) == quicksort(t)) {
return true;
}
else { return false;}
}
public static String quicksort(String s) {
int len = s.length();
int median = len/2; //pivot point
String sortedString;
if (len < 2) {
return s;
}
else {
String str = s.replace(String.valueOf(s.charAt(median-1)), "");
char pivot = s.charAt(median-1);
String less = "";
String greater = "";
for (int i = 0; i < str.length(); i++) {
char pointed = str.charAt(i);
if (pointed <= pivot) {
less += String.valueOf(pointed);
}
else {
greater += String.valueOf(pointed);
}
}
sortedString = quicksort(less) + pivot + quicksort(greater);
return sortedString;
}
}