首页 > 解决方案 > 冒泡排序二维数组按字母顺序Java

问题描述

我能否得到第二双眼睛来告诉我为什么我的数组每次打印时都没有被排序?我正在尝试对 2 x 3 数组( Student [][] 教室 = new Student[2][3]; )进行排序并按姓氏字母顺序排列。我的注释代码如下:

//DECLARES THE CLASSROOM ARRAY 
  public static void sort(Student [][] array) {
      //In order for the loop to work, we must initialize values so that we can "Run" through the variables in our loop. 
      
      int a,b; //These are the variables used during loops. Type integer of positional spot needed. 
     
     
      //We will create a temporary Student called "temporary" 
      //This will host values when and if the "swap" occurs. 
      Student temporary = new Student();
      //The four loop initializing values; such as a, b will loop throughout each value of the area. 
      
      //The first two elements check the elements of the array. 
      //The last two loops run through the entirety of the array to run a compare check. 
      for (a = 0 ; a < 2 ; a++){
          
          for(b = 0 ; b < 3; b++) {
            if (b == 2 && a != 1) {
 
                if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0))
                temporary = array[a][b];
                array[a][b] = array[a+1][0];
                array[a+1][0] = temporary;
            }
            else if (b < 2) 
            {if((array[a][b].getLastName().compareToIgnoreCase(array[a][b+1].getLastName()) > 0)) 
                temporary = array[a][b];
                array[a][b] = array[a][b+1];
                array[a][b+1] = temporary;
            }
                
          }
          }//End-For B Loop
      }//End-For A Loop
  //End-Method Check
  

标签: javabubble-sort

解决方案


看看你的代码格式!始终使用 {}。如果您不使用弯括号,则仅下一行取决于 if。所以你的代码说:

  if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0)){
      temporary = array[a][b];
  }
  array[a][b] = array[a+1][0];
  array[a+1][0] = temporary;

你可能想要的:

  if((array[a][b].getLastName().compareToIgnoreCase(array[a+1][0].getLastName()) > 0)){
      temporary = array[a][b];
      array[a][b] = array[a+1][0];
      array[a+1][0] = temporary;
  }

如果您使用 Eclipse,您可以使用CTRL + SHIFT + F自动格式化。


推荐阅读