Search code examples
javaarraysbubble-sort

How to sort 2D array in Java based on 1D array values


How to sort 1D (String) array and 2D (int) array based on 1D (double) array with Bubble Sort in Java. I managed to sort String array based on double array but can't figure out how to also sort 2D (int) array. Every row in 2D array (grades) represents each students multiple grades. I need to achieve goal by using this kind of structure (three arrays). Everything needs to be sorted depending on finalGrade array.

static void sort(String[] students, int[][] grades, double[] finalGrade) {
        double tempFG;
        String tempStud;
        int t;

        //Bubble Sort
        for (int i=0; i<students.length-1; i++) {
            for (int j=0; j<finalGrade.length-i-1; j++) { 
                if (finalGrade[j] < finalGrade[j+1]) { 
                    tempFG = finalGrade[j];
                    tempStud = students[j];
                    finalGrade[j] = finalGrade[j+1];
                    students[j] = students[j+1];
                    finalGrade[j+1] = tempFG;
                    students[j+1] = tempStud;
                }
           }
        } 
} 

Solution

  • If you must do it in this manner then sorting the 2D array is no harder than sorting any other array. You have to remember that a 2D array is just an array of arrays. i.e just treat the inner array the way you would treat any other object in an array.

        static void sort(String[] students, int[][] grades, double[] finalGrade) {
            double tempFinalGrade;
            String tempStudent; //I think using well descriptive vars is better
            int [] tempGrade;
            
            //Bubble Sort
            for (int i=0; i<students.length-1; i++) {
                for (int j=0; j<finalGrade.length-i-1; j++) {
                    if (finalGrade[j] < finalGrade[j+1]) {
                        tempFinalGrade = finalGrade[j];
                        tempStudent = students[j]; 
                        tempGrade = grades[j];//addition
    
                        finalGrade[j] = finalGrade[j+1];
                        students[j] = students[j+1];
                        grades[j] = grades[j+1]; //addition
    
                        finalGrade[j+1] = tempFinalGrade;
                        students[j+1] = tempStudent;
                        grades[j+1] = tempGrade; //addition
                    }
                }
            }
        }
    

    I will say that I think this is not a good way at all to solve this problem. abstracting this in a class would be much better.