Sorting a 2 dimensional array

匆匆过客 提交于 2020-01-13 18:28:12

问题


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.


回答1:


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];
    }
});



回答2:


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.




回答3:


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.




回答4:


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 );



来源:https://stackoverflow.com/questions/4158679/sorting-a-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!