edward
edward

Reputation: 3

Sorting an 2d array in alphabetical order

I am sorting a 2D array and am having a few issues. When i sort it starts to work for the first couple and doesn't finish. Here is my code then I will post my output.The first part of sectionArray[] contains 2 sections. In the second part of sectionArray[][] contains different student objects. I need to sort these object's String names alphabetically for each section.

public void sortByName(){
    String temp;
    for(int i = 0; i < 2; i++){
        for (int a = 0; a < sectionArray[i].length-1; a++){
            if (sectionArray[i][a].getName().compareToIgnoreCase(sectionArray[i][a+1].getName()) > 0){
                temp = sectionArray[i][a].getName();
                sectionArray[i][a].setName(sectionArray[i][a+1].getName());
                sectionArray[i][a+1].setName(temp);

            }
        }
    }

}

Output:

Progress Report

Section 1

Johnson 90.6  A

Aniston 81.2  B

Cooper_ 82.2  B

Gupta__ 72.2  C

Blair__ 52.2  F

 Section 2

Clark__ 59.2  F

Kennedy 63.4  D

Bronson 90.0  A

Sunny__ 84.8  B

Smith__ 75.4  C

Diana__ 68.8  D

AFTER SORTING THE 2D ARRAY

Progress Report

Section 1

Aniston 90.6  A

Cooper_ 81.2  B

Gupta__ 82.2  B

Blair__ 72.2  C

Johnson 52.2  F

 Section 2

Clark__ 59.2  F

Bronson 63.4  D

Kennedy 90.0  A

Smith__ 84.8  B

Diana__ 75.4  C

Sunny__ 68.8  D

Upvotes: 0

Views: 1718

Answers (1)

jend
jend

Reputation: 106

Perhaps you could just use a comparator :

Arrays.sort(myList, new Comparator<Student>() {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2);
    }

});

Upvotes: 2

Related Questions