简体   繁体   English

按字母顺序选择的2D数组

[英]Alphabetical selection sort of a 2D array

My assignment asks me to store inputted data in a 2D array and use a selection sort to sort the crimes in alphabetical order. 我的作业要求我将输入的数据存储在2D数组中,并使用选择排序按字母顺序对犯罪进行排序。 How can I alter the following selection sort: 如何更改以下选择排序:

//selection sort
    for(i = 0; i < criminal.length; i++){
        smallest = i;

        for(j = i; j < criminal.length; j++){
            //compare smallest to current position
            if(criminal[j] < criminal[smallest]){
                smallest = j;
            }

         //swap smallest with position in the array
         temp = criminal[i];
         criminal[i] = criminal[smallest];
         age[smallest] = temp;

        }


    }           
    //output 
    for(i = 0; i < criminal.length; i++){
        System.out.println(criminal[i]);
    }

So that it can accommodate a 2D array that looks like this: 这样就可以容纳一个二维数组,如下所示:

//loop to request to fill array
    for (i = 0; i < criminals.length ; i++) {               
            System.out.print("Enter first and last name of criminal: ");
            criminals[i][0] = br.readLine(); //Criminal Name

            System.out.print("Enter crime committed: ");
            criminals[i][1] = br.readLine(); //Criminal Crime

            System.out.print("Enter year of conviction: ");
            criminals[i][2] = br.readLine(); //Year of conviction
    }

That's it. 而已。 Any help would be great! 任何帮助将是巨大的! I really need to finish this ASAP. 我真的需要尽快完成此工作。 Thanks in advance. 提前致谢。 :) :)

Depends on what you're sorting on. 取决于您要排序的内容。 If you want to sort the criminals based on their name, then every time you have something like criminal[X] in the selection sort algorithm, replace it with criminal[X][0] . 如果要基于罪犯的姓名对罪犯进行排序,则每次在选择排序算法中有诸如criminal[X]之类的东西时,请将其替换为criminal[X][0] Similarly if you want to sort based on year of conviction replace criminal[X] with criminal[X][2] , etc. 同样,如果您要基于定罪年份进行排序,请使用criminal[X][2]等替换criminal[X]

One note, if you're sorting on strings don't use < , use the compareTo() method instead. 请注意,如果您要对字符串进行排序,请不要使用< ,而应使用compareTo()方法。

You are sorting names, and they happen to have two other fields associated with them. 您正在对名称进行排序,并且它们恰好与其他两个字段关联。 When your sort moves stuff around by swapping indices, it should swap the appropriate indices for the entries (the rows) in criminals[][]. 当您的排序通过交换索引来移动内容时,应该为罪犯[] []中的条目(行)交换适当的索引。

Arrays.sort(criminal, new Comparator<String[]>() {
   @Override
   public int compare(String[] o1, String[] o2) {
      return o1[0].compareTo(o2[0]);
   }        
});

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

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