# Help with 2D array and sorting

Discussion in 'Java' started by datnokka, Mar 22, 2010.

1. ### datnokkaNew Member

Joined:
Mar 22, 2010
Messages:
2
0
Trophy Points:
0
Trying to write a code that creates a 5 x 5 2D array with random numbers from 0-9. Then sorts array columns from lowest to highest top to bottom adding the rows to output a total. Similar to this but with random numbers.

Input array
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1

Output array
1 1 1 1 1 = 5
2 2 2 2 2 = 10
3 3 3 3 3 = 15
4 4 4 4 4 = 20
5 5 5 5 5 = 25

All I have so far is the below 2D 5 x 5 array. Stuck on the sorting and the summing of the rows. Any help would be appreciated.

--------------------------------------------------------------
public
class SortArray {
public static void main(String[] args) {

System.out.print(
"Input Array:");
System.out.println();

int row, col;
int[][] random; // array declaration
random = new int[5][5]; // creation of 5 x 5 array

// fills a 5 x 5 array with random numbers between 0 and 9
for (row = 0; row < scores.length; row++){
for (col = 0; col < scores[row].length; col++){
scores[row][col] = (
int)(Math.random() * 9);
}
}

// prints the contents of the array
for (row = 0; row < scores.length; row++){
for (col = 0; col < scores[row].length; col++){
System.out.print( scores[row][col] +
" ");
}
System.out.println();
// moves to next line
}
}
}

2. ### virxenNew Member

Joined:
Nov 24, 2009
Messages:
387
90
Trophy Points:
0
Code:
```import java.util.Random;

public class SortArray {
public static void main(String[] args) {

System.out.print("Input Array:");
System.out.println();

int row, col;
int[][] scores; // array declaration
scores = new int[5][5]; // creation of 5 x 5 array
Random random = new Random();

// fills a 5 x 5 array with random numbers between 0 and 9
for (row = 0; row < scores.length; row++){
for (col = 0; col < scores[row].length; col++){
scores[row][col] = random.nextInt(10);//0-9 , 9 included
}
}

// prints the contents of the array
for (row = 0; row < scores.length; row++){
for (col = 0; col < scores[row].length; col++){
System.out.print( scores[row][col] + " ");
}
System.out.println(); // moves to next line
}
System.out.println("result sorted");
for (col=0;col< scores[0].length; col++){
for (int i=0;i<scores.length;i++)
for (int j=i;j<scores.length;j++){
if (scores[i][col]>scores[j][col]){
int temp=scores[i][col];
scores[i][col]=scores[j][col];
scores[j][col]=temp;
}
}
}

// prints the contents of the array
for (row = 0; row < scores.length; row++){
for (col = 0; col < scores[row].length; col++){
System.out.print( scores[row][col] + " ");
}
System.out.println(); // moves to next line
}

}

}
```
imagine that every column is a new array.
in this new array perform bubblesort.
do this for all columns.

3. ### datnokkaNew Member

Joined:
Mar 22, 2010
Messages:
2
0
Trophy Points:
0
Thanks so much. I think I can get it from here.