java – 冒泡排序2D数组
发布时间:2020-12-15 02:12:11 所属栏目:Java 来源:网络整理
导读:我需要构建一个冒泡排序2D数组的代码.这里的技巧是我不能使用一维数组助手,或将项目移动到另一个数组. 排序需要在2D阵列上. 现在我建立了我的功能.但是出了点问题.这是我的输出 1 1 2 6 12 32 49 44 54 55 100 344 是接近完成,我不知道该怎么做. public stat
我需要构建一个冒泡排序2D数组的代码.这里的技巧是我不能使用一维数组助手,或将项目移动到另一个数组.
排序需要在2D阵列上. 现在我建立了我的功能.但是出了点问题.这是我的输出 1 1 2 6 12 32 49 44 54 55 100 344 是接近完成,我不知道该怎么做. 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); } } } } } 解决方法
下面是排序2D数组的代码,技巧是您必须将2D数组视为一维数组,然后为索引导出适当的行,偏移对.
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; } } } } } 输出: Started totalCount : 12 Printing output [1,32] [44,49,344] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |