简体   繁体   English

排序2D数组,但将列元素保持在一起

[英]Sorting 2D Array but keeping column elements together

I have a 2D array with 2 rows and n columns. 我有一个2行2列n列的二维数组。

I am trying to sort the array using the built in Arrays.sort method, but I am struggling with the comparator. 我正在尝试使用内置的Arrays.sort方法对数组进行排序,但是我在与比较器进行斗争。 I want to sort the 2D array by the first row, so that the 2nd row elements will remain with the original elements they were aligned with ie. 我想按第一行对2D数组进行排序,以便第二行元素将与原始元素保持对齐,即。 keep the columns together. 保持列在一起。

For example original array: 例如原始数组:

int[] unsortedArray = new int[][]{ { 6, 3, 1, 2, 3, 0}, { 2, 1, 6, 6, 2, 4},

sorted array: 排序数组:

int[] unsortedArray = new int[][]{ { 0, 1, 2, 3, 3, 6}, { 4, 6, 6, 1, 2, 2},

What is the best way to go about doing this? 这样做的最佳方法是什么? Cheers. 干杯。

Try the following: 请尝试以下操作:

Disclaimer: Not tested :) 免责声明:未测试:)

myarray = new int[10][2];

// populate the array here

Arrays.sort(myarray, new Comparator<int[]>() {
    public int compare(int[] a, int[] b) {
        if (a[0] > b[0])
            return 1;
        else if (a[0] < b[0])
            return -1;
        else {
            return 0;
        }
    }
};

You will have to write a custom sort. 您将必须编写一个自定义排序。 Look into Comparable and Comparator . 研究可比比较器

Something along the lines of: 类似于以下内容:

public class MyComparator implements Comparator<T[]> {
    int columnToSortOn;
    public MyComparator(int columnToSortOn) {
        this.columnToSortOn = columnToSortOn;
    }
    @Override
    public int compare(T[] array1, T[] array2) {
        return array1[columnToSortOn].compareTo(array2[columnToSortOn]);
    }
}

Here is an alternative way of keeping your columns aligned. 这是保持列对齐的另一种方法。 This uses a simple class to hold both column elements. 这使用一个简单的类来保存两个列元素。

class TwoInts  {
   public final int aElement;
   public final int bElement;
   public TwoInts(int a_element, int b_element)  {
      aElement = a_element;
      bElement = b_element;
   }
}

One by one, each column (from sub-array one and two) are placed in this object, and immediately put into a Map<Integer,List<TwoInts>> . 每一列(分别来自子数组1和2)一一放置在此对象中,并立即放入Map<Integer,List<TwoInts>> The key is the element from intArrayArray[0] , and the value is a list of TwoInts , because there may be (and in your example code, are) duplicate values in intArrayArray[0] . 关键是从元件intArrayArray[0]并且该值是列表 TwoInts ,因为有可能(和在您的示例代码,都是)中重复的值intArrayArray[0]

You then iterate through the map's key-set, and replace them into the array. 然后,您遍历地图的键集,并将其替换为数组。

Full code: 完整代码:

  import  java.util.ArrayList;
  import  java.util.Arrays;
  import  java.util.Iterator;
  import  java.util.List;
  import  java.util.Map;
  import  java.util.TreeMap;
/**
   <P>{@code java SortOneArrayKeepSecondArrayElementsAligned}</P>
 **/
public class SortOneArrayKeepSecondArrayElementsAligned  {
   public static final void main(String[] ignored)  {
      int[][] intArrayArray = new int[][]{
        { 6, 3, 1, 2, 3, 0},
        { 2, 1, 6, 6, 2, 4}};
      output2DArray("Unsorted", intArrayArray);

      Map<Integer,List<TwoInts>> twoIntMap = new TreeMap<Integer,List<TwoInts>>();
      for(int i = 0; i < intArrayArray[0].length; i++)  {
         int intIn0 = intArrayArray[0][i];
         if(!twoIntMap.containsKey(intIn0))  {
            List<TwoInts> twoIntList = new ArrayList<TwoInts>(intArrayArray.length);
            twoIntList.add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
               twoIntMap.put(intIn0, twoIntList);
         }  else  {
            twoIntMap.get(intIn0).add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
         }
      }

      int idx = 0;
      Iterator<Integer> itr2i = twoIntMap.keySet().iterator();
      while(itr2i.hasNext())  {
         List<TwoInts> twoIntList = twoIntMap.get(itr2i.next());
         for(TwoInts twoi : twoIntList)  {
            intArrayArray[0][idx] = twoi.aElement;
            intArrayArray[1][idx++] = twoi.bElement;
         }
      }

      output2DArray("Sorted", intArrayArray);
   }
   private static final void output2DArray(String description, int[][] twoD_array)  {
      System.out.println(description + ":");
      System.out.println("0: " + Arrays.toString(twoD_array[0]));
      System.out.println("1: " + Arrays.toString(twoD_array[1]));
      System.out.println();
   }

}
class TwoInts  {
   public final int aElement;
   public final int bElement;
   public TwoInts(int a_element, int b_element)  {
      aElement = a_element;
      bElement = b_element;
   }
}

Output: 输出:

[C:\java_code\]java SortOneArrayKeepSecondArrayElementsAligned
Unsorted:
0: [6, 3, 1, 2, 3, 0]
1: [2, 1, 6, 6, 2, 4]

Sorted:
0: [0, 1, 2, 3, 3, 6]
1: [4, 6, 6, 1, 2, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM