Java – bubble sort 2D array
•
Java
I need to build a bubble sort 2D array code The trick here is that I can't use the one-dimensional array helper or move items to another array
Sorting needs to be on a 2D array
Now I have built my function But something went wrong This is my output
1 1 2 6 12 32 49 44 54 55 100 344
It's almost finished. I don't know what to do
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 + 1); } } } } }
Solution
The following is the code for sorting 2D arrays. The trick is that you must treat the 2D array as a one-dimensional array, then export the appropriate rows for the index and offset the pairs
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,32] [44,49,344]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码