# Thread: Need help with 2d array and sorting 1d array

1. Member Join Date
Oct 2011
Posts
16
Rep Power
0

## Need help with 2d array and sorting 1d array

The topic title is a little bit confusing, but here is the excercise description.
Matrix of grades (int[][] g) contains one row per student where elements of the row are grades (in scale 0 to 5) of corresponding student. Write a Java method to calculate an array of row indices in descending order of average grade, in case of equal averages the row that has smaller index comes first.
I just can't think a way what to do next. I appreciate if somebody could help me :)

Java Code:
```package Sone_matrix;

import java.util.Arrays;

public class matExample4 {

//On antud hinnete maatriks (int[][] g), milles on iga
//üliõpilase jaoks üks rida, mille elementideks on selle
// üliõpilase binded (skaalal 0 kuni 5). Koostada Java meetod
//üliõpilaste pingerea moodustamiseks, mis tagastaks reanumbrite
//massiivi (kõrgeima keskhindega reast allapoole, võrdsete korral
//jääb ettepoole see rida, mille number on väiksem).

public static void main(String[] args) {
int res [] = sortByAvg(new int [][] {{3,3,3},{2,2,2},{4,4,4},{2,2,2}});//0,1,2
System.out.print(Arrays.toString(res));
}

public static int [] sortByAvg(int [][] m ) {
int [] result = new int[m.length];
int temp;

//Võtame keskmised hinded
for(int i=0;i<m.length;i++) {
for(int j=0;j<m[i].length;j++ ) {
result[i] +=m[i][j];
}
result[i] = result[i]/m[i].length;
System.out.print(+i);
}
//Sorting array so that lower average grades will be first

return result;
}

}```  Reply With Quote

2. ## Re: Need help with 2d array and sorting 1d array

Look at using the contents of one array to index another array. The syntax would be something like this:
anArray[anotherArray[j]]

Then take a piece of paper and work out the logic for doing a sort using this type of variable references.  Reply With Quote

3. Member Join Date
Oct 2011
Posts
16
Rep Power
0

## Re: Need help with 2d array and sorting 1d array

Could i get one hint more ;) I am still a little bit confused.  Reply With Quote

4. ## Re: Need help with 2d array and sorting 1d array

Break the problem up into several steps.
One step is to get the averages for each student.
The next step is to create an array of indexes.
Say the averages are {33, 555, 22}
then the array of indexes would be {2(index of 22), 0(index of 33), 1 (index of 55)}
Look at the logic of sorting the indexes original order {0,1,2} to that get the above order.
Use lots of paper and pencil to work this out.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•