简体   繁体   English

为什么我的改进气泡排序方法不起作用?

[英]Why doesn't my ImprovedBubbleSort method work?

This is my java code for array exercises at my school and I was wondering why even though everything here works when I try to use the ImprovisedBubbleSort method my program stops functioning这是我在学校进行数组练习的 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]);
    }
  }  
}

It's important to realize that if you're using a single loop like in your example with that if statement you can find an instance of position 0 and 1 where it is sorted but the rest of the array may not be sorted.重要的是要意识到,如果您在示例中使用 if 语句中的单个循环,您可以找到位置 0 和 1 的实例,在该位置对其进行排序,但数组的其余部分可能未排序。 This will cause the if statement to not activate.这将导致 if 语句无法激活。

You can alleviate this problem by doing something like this:您可以通过执行以下操作来缓解此问题:

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

See this example.请参阅示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM