java - Implement the following method to sort the rows in a twodimensional array -
i have been working on problem day , cannot find out next. have sorting rows not sort last row completely. here code.i know once or gets feel stupid .thank you
public class sort2drow { public static void main (string [] args) { int[][] matrix = {{3,5,6}, {4,1,2},{9,8,7}}; system.out.println("before sort"); for(int row = 0; row <matrix.length; row++){ for(int col = 0; col <matrix[row].length; col++){ system.out.print(matrix[row][col] + " "); } system.out.println(); } system.out.println();//spacer system.out.println("after sort method"); sortrow(matrix); } public static int[][] sortrow(int[][] m) { int temp = 0; for(int row = 0; row < m.length ; row++) { for(int col = 0; col < m.length -1; col++){ if(m[row][col] > m[row][col + 1]) { temp = m[row][col]; m[row][col] = m[row][col + 1]; m[row][col + 1] = temp; } } } for(int row = 0; row <m.length; row++){ for(int col = 0; col <m[row].length; col++){ system.out.print(m[row][col] + " "); } system.out.println(); } int[][] result = m; return result; } }
you're on right track, problem you're mistakenly assuming for(int row = 0; row < m.length ; row++)
outer bubblesort loop. it's loop "loads" next row in 2-d array. you'll need add missing loop:
for(int col = 0; col < m[row].length; col++){ //this real outer bubblesort loop. change m[row].length for(int nextcol = col; nextcol < m[row].length; nextcol++) { if(m[row][col] > m[row][nextcol]) { temp = //i'll let figure out m[row][col] = //.... m[row][nextcol] = //... } } }
Comments
Post a Comment