# sorting only 1 column of 2D array

• March 24th, 2013, 10:21 PM
bczm8703
sorting only 1 column of 2D array
hi.. i am trying to sort my 2D array such that only the 2nd column get sorted.. i tried to use Arrays.sort(arr[a]) but it seem to sort the whole array

example of what i want:
before sort
a[0][0]= 9 a[1][0] = 50
a[0][1]= 5 a[1][1] = 5
a[0][2]= 3 a[1][2] = 78
a[0][3]= 6 a[1][3] = 23
a[0][4]= 2 a[1][4] = 67

aft sort
a[0][0]= 2 a[1][0] = 5
a[0][1]= 3 a[1][1] = 23
a[0][2]= 5 a[1][2] = 50
a[0][3]= 6 a[1][3] = 67
a[0][4]= 9 a[1][4] = 78

the code i m using now
Code :

``` for (int i=0;i<dist.length;i++) { Arrays.sort(dist[i]); }```

output of current code:
before sort
a[0][0]= 9 a[1][0] = 50
a[0][1]= 5 a[1][1] = 5
a[0][2]= 3 a[1][2] = 78
a[0][3]= 6 a[1][3] = 23
a[0][4]= 2 a[1][4] = 67

aft sort
a[0][0]= 2 a[1][0] = 9
a[0][1]= 3 a[1][1] = 23
a[0][2]= 5 a[1][2] = 50
a[0][3]= 5 a[1][3] = 67
a[0][4]= 6 a[1][4] = 78
• March 25th, 2013, 06:08 AM
Norm
Re: sorting only 1 column of 2D array
Can you post the definition of an array to sort as java code for testing?
• March 25th, 2013, 11:34 PM
bczm8703
Re: sorting only 1 column of 2D array
Code :

` double[][] a1 = new double[][] {{2.5,3.6,0.7,0.01},{0.85,1.32,0.20,0.992}};`

based on this the output after sorting should be
a1[0][0] = 0.01 a1[1][0] = 0.20
a1[0][1] = 0.7 a1[1][0] = 0.85
a1[0][2] = 2.5 a1[1][0] = 0.992
a1[0][3] = 3.6 a1[1][0] = 1.32
• March 26th, 2013, 06:21 AM
Norm
Re: sorting only 1 column of 2D array
When I execute this code:
Code :

``` double[][] dist = new double[][] {{2.5, 3.6, 0.7, 0.01},{0.85, 1.32, 0.20, 0.992}}; System.out.println("B="+Arrays.deepToString(dist)); for (int i=0;i<dist.length;i++) { Arrays.sort(dist[i]); } System.out.println("A="+Arrays.deepToString(dist));```
I get this printed:
Quote:

B=[[2.5, 3.6, 0.7, 0.01], [0.85, 1.32, 0.2, 0.992]]
A=[[0.01, 0.7, 2.5, 3.6], [0.2, 0.85, 0.992, 1.32]]
It looks sorted to me.
• March 26th, 2013, 06:38 AM
bczm8703
Re: sorting only 1 column of 2D array
Quote:

Originally Posted by Norm
When I execute this code:
Code :

``` double[][] dist = new double[][] {{2.5, 3.6, 0.7, 0.01},{0.85, 1.32, 0.20, 0.992}}; System.out.println("B="+Arrays.deepToString(dist)); for (int i=0;i<dist.length;i++) { Arrays.sort(dist[i]); } System.out.println("A="+Arrays.deepToString(dist));```
I get this printed:

It looks sorted to me.

Weird... As stated in my first post. I tried your method and did not get your result. Will check where I did wrong
• March 26th, 2013, 10:27 PM
bczm8703
Re: sorting only 1 column of 2D array
thanks for all the help... think the error i 1st encounter is my stupid self trying to display a shorter version of my array.. did not realise that the value is hidden in the array index i did not wan to be displayed out...