Search code examples
javaarrayssortingbubble-sort

2d array ascending bubblesort java


I am trying to implement bubble sort on a 2D array to put the rows in ascending order, but it is only moving the first item. How can I fix this?

for(int i = 0; i<differencearray.length; i++){
        for(int j = 0; j<differencearray[i].length-1; j++){
            if(differencearray[i][j]>differencearray[i][j+1]){
                int temp = differencearray[i][j];
                differencearray[i][j] = differencearray[i][j+1];
                differencearray[i][j+1] = temp;
                }
        }
    }

The input is:

2147483647 15 9 13 24 

15 2147483647 18 16 17 

9 18 2147483647 12 27 

13 16 12 2147483647 25 

24 17 27 25 2147483647 

The output is:

15 9 13 24 2147483647 

15 18 16 17 2147483647

9 18 12 27 2147483647

13 12 16 25 2147483647 

17 24 25 27 2147483647 

Any help would be great!


Solution

  • Bubble sort is an O(n^2) algorithm so you need 2 for loops for a single array.

    If you have n arrays then you would need 3 for loops in order to sort all the rows.

    Which makes it O(n^2*m) algorithm. ( where m is the amount of rows)

    Soooo...

     for(int i = 0; i < rowCount; i++){
       for(int j = 0; j < colCount; j++){
         for(int k = 0; k < colCount; k++){
           if(differencearray[i][k]>differencearray[i][k+1]){
                int temp = differencearray[i][k];
                differencearray[i][k] = differencearray[i][k+1];
                differencearray[i][k+1] = temp;
           }
    
         }
       }
     }