0
int [][] div = {
                 {1, 1, 2},
                 {2, 1, 2},
                 {1, 2, 2},
                 {3, 1, 2},
                 {1, 2, 3},
                 {2, 1, 1},
                 {1, 1, 1}
               };

I want to sort this array according to the first column.

I've done something but I messed up. I really don't know how to swap the other columns together with the first column.

for(int x = 0; x < div.length-1; x++) {
  for(int y = 0; y < div.length-1;y++) {
    if(div[y][0] > div[y+1][0]) {
      tmp = div[y][0];
      div[y][0] = div[y+1][0];
      div[y+1][0] = tmp;
    }                   
  }
}
for(int x = 0; x < arr.length; x++) {   
  System.out.print(div[x][0]+" \t" + div[x][1] + "\t"+ div[x][2] +  "\n");          
}

1 Answer 1

4

You were close but messed up the swap, tmp=div[y][0] is an integer, but you want to swap an array.

Consider div[][] to be an array of arrays, if you want to swap an array inside of it with another, you need a tmp value that is an array not just an int so :

int[] tmp;    

    for (int x = 0; x < div.length - 1; x++) {

                if (div[x][0] > div[x + 1][0]) {
                    tmp = div[x];
                    div[x] = div[x + 1];
                    div[x + 1] = tmp;

                }

            }

To print the array:

 for(int x = 0; x < div.length; x++)
 {   
     for(int y = 0; y < div[x].length;y++)
        {
           System.out.print(div[x][y]+" ");
        }
     System.out.println();    


  }
Sign up to request clarification or add additional context in comments.

5 Comments

tmp should be int [] tmp its being set to an array of int not a 2d array of ints
so what would i print, tmp or the array div?
Printing depends on the format you want, just access the values inside div[][] like you did while sorting and print them. tmp is just a temporary value you use for the swap
what if i want to print the whole sorted array?
@noviceJ sorry my answer was wrong, tried it now to make sure , should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.