为什么我的ImprovedBubbleSort方法不起作用?

时间:2018-02-13 01:17:00

标签: java

这是我在学校进行数组练习的java代码 而且我想知道为什么即使我尝试使用ImprovisedBubbleSort方法时这里的一切都有效,我的程序也会停止运行

 public static void ImprovedBubbleSort(int [] array){
    boolean swap;
    int temp;
    int max;
    do {
      swap=false;
      max=1;
      for (int i=0;i<array.length-max;i++){
        if (array[i]>array[i+1]){
          temp=array[i];
          array[i]=array[i+1];
          array[i+1]=temp;
          swap=true;
        }
        max++;
      }
    }while (swap=true);
    System.out.println("The numbers you entered in order are: ");
    for (int j=0;j<10;j++){
      System.out.println(array[j]);
    }
  }  
}

1 个答案:

答案 0 :(得分:1)

重要的是要意识到,如果您使用单个循环,就像在您的示例中使用if语句一样,您可以找到位置0和1的实例,其中它被排序但是数组的其余部分可能没有排序。这将导致if语句不激活。

您可以通过执行以下操作来缓解此问题:

import java.util.Arrays;
public class MyClass {
    public static void main(String args[]) {


    int test[] = {7,1,9,1,5,6};
    bubbleSort(test);
    System.out.println(Arrays.toString(test));
    }

    static void bubbleSort(int[] arr) {  
        int n = arr.length;  
        int temp = 0;  
        for(int i=0; i < n; i++){  
            for(int j=1; j < (n-i); j++){  
                if(arr[j-1] > arr[j]){  
                    //swap elements  
                    temp = arr[j-1];  
                    arr[j-1] = arr[j];  
                    arr[j] = temp;  
                }  
            }  
        }  
    }
}

请参阅this示例。

相关问题