# Sort two dimension array

Page 1 of 1

## 1 Replies - 1791 Views - Last Post: 25 November 2009 - 09:07 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=141585&amp;s=54fb4362cf896029bf2fdf686ef4cf6a&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 danielp

Reputation: 0
• Posts: 4
• Joined: 03-November 09

# Sort two dimension array

Posted 25 November 2009 - 07:22 PM

Im trying to sort a two dimensional array in ascending order, something like;
4 3 2
9 7 2
1 5 6 is the original

1 2 2
3 4 5
6 7 9 the new one

iknow how to sort one dimension arrays but i cannot figure out how to do it when using two dimensions, so far ive tried to modify the single dimension code into the other but it doesnt work or im doing it wrong
im doing it in spanish, so matriz = array
any help would be appreciated

```   int i, j, tempo, tampo2;

for(i=0; i<fil; i++)
for (j=0; j<col; j++)
temp [i][j] = matriz[i][j];

for(i=0; i<fil; i++)
for (j=0; j<col; j++)
if (temp[i][j] < temp [i+1][j])
tempo = temp [i][j];
temp[i][j] = temp [i+1][j];
temp [i+1][j] = tempo;

```

Is This A Good Question/Topic? 0

## Replies To: Sort two dimension array

### #2 pbl

• There is nothing you can't do with a JTable

Reputation: 8362
• Posts: 31,955
• Joined: 06-March 08

## Re: Sort two dimension array

Posted 25 November 2009 - 09:07 PM

That should so it

```		int[][] original = { {7,8,9}, {3,2,1}, {6,4,5}};

// build single array out of 2D one
// (this is assuming all rows have the same length)
int[] x = new int[original.length * original[0].length];
// index in new array
int k = 0;
// copy it
for(int i = 0; i < original.length; i++) {
for(int j = 0; j < original[i].length; j++) {
x[k++] = original[i][j];
}
}
// sort the single one
Arrays.sort(x);
// relaod the new one
int[][] sorted = new int[original.length][original[0].length];
k = 0;
for(int i = 0; i < sorted.length; i++) {
for(int j = 0; j< sorted[i].length; j++) {
sorted[i][j] = x[k++];
System.out.print("	[" + i + "][" + j + "] = " + sorted[i][j] );
}
System.out.println();
}

```