简体   繁体   中英

Java sorting parallel arrays

I have to sort a database of 1 string array and 2 int arrays. This is what I have so far:

public static void sortDatabase(int numRecords, String[] sDeptArr, 
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       int length = sDeptArr.length;
       for(int i=0; i<length-1; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<length; j++)
           {
               if(sDeptArr[j].compareTo(sDeptArr[iPosMin]) == 0)
                   iPosMin = j;
               else if(sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
       }
   }

I have yet to test it because the entire program is not done but does this look like it is going in the right direction? I want to sort the database in alphabetical order by name first, then if the names are the same, use the course number to sort.

IMHO your direction is not optimal. The best way I know is to create new data structure

public class Data implements Comparable<Data> {
    private String sDeptArr;
    private int iCourseNumArr;
    private int iEnrollmentArr;

    public int compareTo(Data other) {
    // your implementation
    }
}

Now create an array or collection of Data:

List<Data>
Data[]

Now use Arrays.sort() or Collections.sort() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM