Bubble-Sort Two-Dimensional Array

I need to create code that a bubble sorts a 2D array. The trick here is that I cannot use the one-dimensional array helper or move elements to another array.

Sort must be in a 2D array.

Now I have built my function. But something is going wrong. This is my conclusion.

1      1      2      6     12     32
 49     44     54     55    100    344

close to completion, and I can’t think how to do it.

 public static int [] [] sortMatrix(int[][]matrix){
    for(int x = matrix.length  ; x >0  ; x-- ){
        for(int i = matrix[0].length  ; i > 0 ; i-- ){
            for(int j = 0 ; j < x  ; j++){
                for(int t = 0 ;t < i    ;  t++){
                    if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
                        swap(matrix , j , t, t+1);
                    }
                    else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
                        swap1(matrix ,j , t , j + 1);
                    }                       
                }
            }               
        }           
    }
+4
source share
1 answer

Below is the code for sorting a 2D array, the trick is that you should think of the 2D array as a single array, and then output the corresponding rows, offset pairs for the indices.

import java.util.Arrays;    

public class Bubble2DSort {
    public static void main(String[] args) {
        System.out.println("Started");

        int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};

        sortMatrix(matrix);

        System.out.println("Printing output ");

        for(int[] rowArr : matrix) {
            System.out.println(Arrays.toString(rowArr));
        }
    }

    private static void sortMatrix(int[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;
        int totalCount = row * col;

        System.out.println("totalCount : " +totalCount);

        boolean noSwaps = false;
        for(int i = 0; !noSwaps; i++) {
            noSwaps = true;

            for(int j = 1; j < totalCount - i; j++) {
                int currentRow = (j-1) / col;
                int currentOffset = (j-1) % col;
                int nextRow = j / col;
                int nextOffset = j % col;

                if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
                    //swapping
                    int temp = matrix[nextRow][nextOffset];
                    matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
                    matrix[currentRow][currentOffset] = temp;

                    noSwaps = false;
                }
            }
        }
    }
}

Output:

Started
totalCount : 12
Printing output 
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]
0
source

Source: https://habr.com/ru/post/1621734/


All Articles