简体   繁体   English

Java排序并行数组

[英]Java sorting parallel arrays

I have to sort a database of 1 string array and 2 int arrays. 我必须对1个字符串数组和2个int数组的数据库进行排序。 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() . 现在使用Arrays.sort()Collections.sort()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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