冒泡排序比较方法未运行

时间:2015-03-16 17:56:59

标签: java arrays sorting

这是我昨天问过的上一个问题的后续行动。我写了一个冒泡排序方法,它分析一个字符串数组,并返回该方法在按字母顺序排序时所做的比较次数(分配是编写几种类型的排序方法,并绘制每个排序方法的比较数量) ,看看哪个是最有效的。)

这是我的代码:

  public static void main(String[] args)
  {

    String[] test_array = {"bill", "phil", "adam"};
    /*
    System.out.println(compare("orange", "boogie"));
    */

    System.out.println(bubbleSort(test_array));
  }

public static int compare(String a, String b)
{
    int len = Math.min (a.length(),b.length());
    // looping through every character. If cha is less than chb, the method returns -1, and so on.
    for (int i = 0; i<len; i++) {
        char cha = a.charAt(i);
        char chb = b.charAt(i);
        if (cha < chb) {
            return -1;
        } else if (cha > chb) {
            return 1; 
        }
    }
    // Now we account for the length of the word, since it could be the same word.
    if (a.length() < b.length())
        return -1;
    else if (a.length() > b.length())
        return 1;
    // Seems to be the same String, so return 0. 
    else
        return 0;
}

  public static int bubbleSort(String[] test_array) {
    boolean swapped = true;
    // Variable to track number of comparisons. 
    int compNumber = 0;
    while (swapped == true) { 
      swapped = false;
      for (int i = 1; i < test_array.length; i++) {
        // Tracking the number of comparisons
        compNumber++;

        if (compare(test_array[i-1], test_array[i]) > 0) {
          //Switching the variables by use of a temp variable
          String temp = test_array[i-1];
          test_array[i-1] = test_array[i];
          test_array[i] = temp;
          swapped = true;
        }
        else {
         swapped = true; 
        }
      }
    }
    return compNumber; 
  }

因此compare方法比较两个字符串(由数组给出)并确定它们是按字母顺序排列(返回-1)还是不是(返回1),或者是相同的单词(返回0)。然后,冒泡排序方法调用compare方法来遍历数组,然后生成开关,而我的compNumber变量计算循环次数(因此比较次数)的运行次数。

编译很好,但不幸的是它不会停止运行并且不会返回任何内容。我等了5分钟,所以我确定出了问题,可能是我的循环。我似乎找不到问题,多次操纵循环的参数。任何人都可以帮我吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

“swapped”将始终为true,因此while将永远不会结束循环。 我想你的意思是把swapped = false放在else语句

答案 1 :(得分:0)

你需要设置这两个中的一个swapped = false ...否则你永远不会退出while循环 because swapped = true always ...可能改变第二个有意义!

if (compare(test_array[i-1], test_array[i]) > 0) {
          //Switching the variables by use of a temp variable
          String temp = test_array[i-1];
          test_array[i-1] = test_array[i];
          test_array[i] = temp;
          swapped = true;
        }
        else {
         swapped = true; 
        }