Search code examples
javabubble-sort

Can't seem to figure out why bubble sort is not working in java


public static void main(String[] args) {

    int a[]={13,33,1,32,8,10,11,6};
    bubbleSort(a);


}

public static void bubbleSort(int []a){
int temp=0;
    int n= a.length;
    for(int i=0;i<n;i++ ){

        for(int j=1; j<n-1;j++){  

            if(a[j-1]>a[j]){

                temp=a[j-1];
                a[j-1]=a[j];
                a[j]=temp;

            }
        }System.out.println(a[i]);
    }
}

I don't seem to get how do i manage to get such random sort out of the algorithm!? 1 and 8 don't even appear at all and 13 shows 3 times.

THE RESULT : 13 13 10 11 13 32 33 6


Solution

  • There are 2 mistakes I could found.

    • I remove your print statement and put it outside of the loop.
    • Your second loop looks like this. for(int j = 1; j < n - 1; j++){ I replaced with this code line. for (int j = 1; j < (n - i); j++) {

    Plase, try following code.

    public class BubbleSort{
    
       public static void main(String[] args) {
    
          int a[] = {13, 33, 1, 32, 8, 10, 11, 6};
          bubbleSort(a);
    
       }
    
       public static void bubbleSort(int[] a) {
          int temp = 0;
          int n = a.length;
    
          for (int i = 0; i < n; i++) {
             for (int j = 1; j < (n - i); j++) {
                if (a[j - 1] > a[j]) {
                   //swap elements  
                   temp = a[j - 1];
                   a[j - 1] = a[j];
                   a[j] = temp;
                }
    
             }
    
          }
          // print array after sorting. 
          for (int i = 0; i < a.length; i++) {
             System.out.print(a[i] + " ");
          }
       }
    
    }