When I try to use my Compare method in my Bubblesort code to determine the alphabetical order of strings to sort, I get stuck in an infinite loop in the Compare method, which works otherwise.
Any ideas? Thanks!
public static int Compare(String s1 , String s2) { //compares two strings alphabetically
int result = 0 ;
String newS1 = "";
String newS2 = "";
for (int i = 0; i< s1.length(); i++){ //loop converts strings from uppercase to lowercase
char s1Char = s1.charAt(i);
if (65 <= s1Char && s1Char <=90){
s1Char = (char)( (s1Char + 32) );
}
newS1 = newS1 + s1Char;
}
for (int i = 0; i< s2.length(); i++){
char s2Char = s2.charAt(i);
if (65 <= s2Char && s2Char<=90){
s2Char = (char)( (s2Char + 32) );
}
newS2 = newS2 + s2Char;
}
for (int i = 0 ; i <newS1.length();){ //compares the two lowercase strings by ascii value
if (newS1.charAt(i) < newS2.charAt(i)){
result = -1 ;
System.out.println(newS1+ " is before " +newS2+ " in the dictionary");
break ;
}
if (newS1.charAt(i) > newS2.charAt(i)){
result = 1 ;
System.out.println(newS2+ " is before " +newS1+ " in the dictionary");
break ;
}
if (newS1.charAt(i) == newS2.charAt(i)) {
i++ ;
}
else {
result = 0 ;
System.out.println("The words are the same.");
break ;
}
}
return result ;
}
public static int bubbleSort(String[] input_array) { //sorts an array alphabetically
int n = input_array.length ;
String temp = "" ;
int comparisons = 0 ;
boolean swap = false ;
while (swap == true) {
swap = false ;
for(int i = 1 ; i < input_array.length - 1 ; ){
if(Compare(input_array[i] , input_array[i+1]) == -1) { //use compare method above
comparisons++ ;
temp = input_array[i] ;
input_array[i] = input_array[i-1] ; //swap if sorting needed
input_array[i-1] = temp ;
swap = true ;
System.out.println(input_array);
i++ ;
}
else {
i++ ;
}
}
}
return comparisons;
}
public static void main(String[] args) { // used to test code
String[] testArray = {"b" , "c" ,"e" , "d"} ;
bubbleSort(testArray) ;
}