2-dimensional array sorting

I have a 2D array that I would like to sort in descending order depending on the contents of the first column, however I would like the array to save each row and move the second column as the first steps. To give it an example,

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

will be sorted by address:

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

Thank.

+3
source share
4 answers
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
source

Try the following:

    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 have not tested this, but it should work. Please note that you can cancel the subtraction to change the top-down.

+4
source

, Radix Sort. C :

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

. , . ROW NUMBER.

+1

java, . , ( ) .

int var [n] [2]// int
//[[ ]]
//
// ,
int temp [2];
bool stillSorting = true,

{

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

     
  

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

         
    

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

    
0
source

Source: https://habr.com/ru/post/1774385/


All Articles