调用方法时无限循环

时间:2014-10-26 16:36:01

标签: java infinite-loop bubble-sort

当我尝试在Bubblesort代码中使用我的Compare方法来确定要排序的字符串的字母顺序时,我会陷入Compare方法的无限循环中,否则它会起作用。

有什么想法吗? 谢谢!

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) ;
}

2 个答案:

答案 0 :(得分:1)

这里你指定swap等于true。

 while (swap = true) {

我想你想比较它。

boolean swap = true;
while (swap == true){ //Or better while (swap){
   swap = false;

答案 1 :(得分:0)

我认为if内的最后一个Compare应始终为true,因此else永远不会执行。

但我看到的主要问题是Swap无法工作。

ij是对字符串的引用的副本,字符串本身是不可变的。 在Swap的末尾,i指向j最初指向的字符串,反之亦然,但字符串本身没有改变,数组中包含它们相同的地点。

如果您需要单独的Swap方法,请改为传递数组和索引。