Search code examples
javaarraysbubble-sort

Bubble sort on 2D Array Java


String[][] 2dArray = new String[counter][2];
2dArray [counter][column1] = String.valueOf(counter);
2dArray [counter][column2] = "something something something";
for(int i = 0; i < 2dArray.length-1; i++){
     for(int j = i + 1; j > 0; j--){
       if(2dArray[i][j] < 2dArray[i-1][j]){ 
           int[][] temp = 2dArray[i-1][j];
           2dArray[i-1][j] = 2dArray[i][j];
           2dArray[i][j] = temp;                  
       }
     }
}

Attempting to sort the array so that column 1 is ascending. I've studied the other references on here and mimic'd them but for some reason my IDE does not like the above...


Solution

  • If I understand you correctly, I would suggest the following:

    What you would need to do is to compare the Integer values of the array:

    if(Integer.valueOf(2dArray[i][0]) < Integer.valueOf(2dArray[i-1][0])){
    

    The reason you don't include j is because you are only sorting by the value of the first column. 2dArray[i][0] gets you the value of your counter at that particular row.

    I've also seen some other stuff in your code that could use fixing:

    for(int i = 0; i < 2dArray.length; i++){
      for(int j = i; j < 2dArray.length; j++){
        if(Integer.valueOf(2dArray[j][0]) > Integer.valueOf(2dArray[j+1][0])){
           String temp[] = 2dArray[j+1];
           2dArray[j+1] = 2dArray[j];
           2dArray[j] = temp;                  
        }
      }
    }
    

    This is more in line with what I think is the classic implementation of BubbleSort:

    private static void bubblesort(Integer[] array) {
        for (int i = 0; i < array.length; i++) {
            for(int j = 0; j < array.length - 1; j++) {
                if(array[j].compareTo(array[j+1]) > 0) {
                    swap(j, j+1, array);
                }
            }
        }
    
    }
    
    private static void swap(Integer index1, Integer index2, Integer[] array) {
        if(index1 == index2)return;
        Integer temp = new Integer(array[index2]);
        array[index2] = array[index1];
        array[index1] = temp;
    
    }
    

    Except in your case, I'm treating your array as a one-dimensional, since you are only sorting by one dimension.