siame
siame

Reputation: 8657

Sorting a 2 dimensional array

I've got a 2D array that I'd like to sort into descending order depending on the contents of the first column, however I'd like the array to retain each row and move the second column as the first moves. To put it into an example;

[2, 5]
[4, 18]
[1, 7]
[9, 3]

would be sorted into:

[9, 3]
[4, 18]
[2, 5]
[1, 7]

Thanks.

Upvotes: 3

Views: 10333

Answers (4)

itsme
itsme

Reputation: 193

It's nothing but Radix Sort. Its C code is as follows:

void Rsort(int *a, int n)
{
  int i, b[MAX], m = a[0], exp = 1;
  for (i = 0; i < n; i++)
  {
    if (a[i] > m)
      m = a[i];
  }

  while (m / exp > 0)
  {
    int bucket[10] =
    {  0 };
    for (i = 0; i < n; i++)
      bucket[a[i] / exp % 10]++;
    for (i = 1; i < 10; i++)
      bucket[i] += bucket[i - 1];
    for (i = n - 1; i >= 0; i--)
      b[--bucket[a[i] / exp % 10]] = a[i];
    for (i = 0; i < n; i++)
      a[i] = b[i];
    exp *= 10;
 }
}

Here it's operating on digits of the numbers in array. It's not much harder to edit the code to get code for the above problem. Here each element of the array is considered as a digit for that ROW NUMBER.

Upvotes: 1

Bj&#246;rn
Bj&#246;rn

Reputation: 29381

int[][] d2 = {
           {2,5},
           {4,18},
           {1,7},
           {9,3}
          };

java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
    public int compare(int[] a, int[] b) {
        return b[0] - a[0];
    }
});

Upvotes: 2

NMPrado
NMPrado

Reputation: 31

I can't speak to java specifically but the algorithm should be translatable. The point is to move both elements (or more) of the row when swapping.

int var[ n ][ 2 ] // your int array
// [[ choose a sort method ]]
// I'm going to use a bubble sort
// for clarity, despite inefficiency
int temp[ 2 ];
bool stillSorting = true;
do
{

stillSorting = false;
for ( int x = n; x < 1; x-- )
{

if ( var[ x ][ 0 ] > var[ x-1 ][ 0 ] )
{

temp[ 0 ] = var[ x ][ 0 ]; // if it's more than 2
temp[ 1 ] = var[ x ][ 1 ]; // consider using a loop
var[ x ][ 0 ] = var[ x-1 ][ 0 ];
var[ x ][ 1 ] = var[ x-1 ][ 1 ];
var[ x-1 ][ 0 ] = temp[ 0 ];
var[ x-1 ][ 1 ] = temp[ 1 ];
stillSorting = true;
}
}
}
while( stillSorting );

Upvotes: 0

Amir Raminfar
Amir Raminfar

Reputation: 34150

Try this:

    int[][] test = new int[][]{{2,5}, {4,18}, {1,7},{9,3}};
    Arrays.sort(test, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

I haven't tested this but it should work. Note you may want to reverse the subtraction to change descending.

Upvotes: 4

Related Questions