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

 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 answer

  • answered 2018-02-13 01:16 Artemis

    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. This will cause the if statement to not activate.

    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.