Sort two dimension array

sort the integers of the array

Page 1 of 1

1 Replies - 1595 Views - Last Post: 25 November 2009 - 09:07 PM Rate Topic: -----

#1 danielp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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  Icon User is offline

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

Reputation: 8324
  • View blog
  • Posts: 31,857
  • 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();
		}


:D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1