Search code examples
sortingmultidimensional-arraybubble-sort

2d array Bubble sort fix pls



so if you input 3x3 array it should be like this 987 654 321

and i want to bubble sort it to 123 456 789

but i have problem on end line can anyone help me

When I execute my code, the output looks like this:

Please enter number of rows:2
Please enter number of columns: 2
Please enter 4 numbers to sort: 8 4 6 2
Sorted numbers:
[[I@776ec8df [[I@776ec8df [[I@776ec8df [[I@776ec8df

import java.util.Scanner;
public class 2dsort 
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Please enter number of rows: ");
        var row = sc.nextInt();
        
        System.out.print("Please enter number of columns: ");
        var col = sc.nextInt();
        
        int[][] matrix = new int[row][col];
        
        System.out.print("Please enter " + (row*col) + " numbers to sort: ");
        
        for(int x = 0; x < row; x++)
            for(int y = 0; y < col; y++)
            {
                matrix[x][y] = sc.nextInt();
            }
        
        for(int x = 0; x < matrix.length; x++)
            for (int y = 0; y < matrix[x].length; y++)
                for(int t = 0; t < matrix[x].length - y - 1; y++)
                    if(matrix[x][t] > matrix[x][t+1])
                    {
                        int temp = matrix[x][t];
                        matrix[x][t] = matrix[x][t+1];
                        matrix[x][t + 1] = temp;
                    }
    
        //I think this is my problem but idk how to fix
        System.out.println("Sorted numbers:");
        for(int x = 0; x < matrix.length; x++)
            for (int y = 0; y < matrix[x].length; y++)
            System.out.print(matrix + " ");
        System.out.println();
            
    }
}

Solution

  • Your issue appears to be here:

    System.out.print(matrix + " ");

    You're not printing out the values held by the matrix.

    You likely want to retrieve the values at the specific indices using matrix[x][y]

    I ran your code using System.out.print(matrix[x][y] + " "); and while the code execution worked and printed the matrix values appropriately, your sorting algorithm isn't giving you the results you want. I'll leave that for you to fix, but your printing issue is solved.