2015-02-11 59 views
0

我需要排序一个二维arrylist Java和获取排序元素的索引。要做到这一点我 1.第一次写这个代码,我做一个普通类数组元素进行排序,并获得排序元素的原始指数:排序2d arraylist和得到索引java

public static int[] Sort_Index(double[] arr){ 
      int[] indices = new int[arr.length]; 
       indices[0] = 0; 
       for(int i=1;i<arr.length;i++){ 
        int j=i; 
        for(;j>=1 && arr[j]<arr[j-1];j--){ 
          double temp = arr[j]; 
          arr[j] = arr[j-1]; 
          indices[j]=indices[j-1]; 
          arr[j-1] = temp; 
        } 
        indices[j]=i; 
       } 
       return indices;//indices of sorted elements 
     } 

然后我用这个循环来安排的ArrayListÿ

for(int i=0;i<Input.General_Inputs.Num_objectives;i++){ 
      double[] sort_y=new double[y.size()]; 
      for(int row=0;row<y.size();row++) 
       sort_y[row]=y.get(row).get(Input.General_Inputs.Num+i); 
      int[] sort_y_index=Sort_Index(sort_y); 

     } 
    } 

对我来说,下一步就是使用这个索引将y ArrayList中的值存储到新的ArrayList中。但我认为这是完全没有效率的更好的想法?

回答

0

您可以创建一个类包装原始指数:

private static class ElementWithIndices<E> { 
    private final E e; 
    private final int i; 
    private final int j; 
    // + constructor, getters, setters 
} 

然后:

List<List<E>> list = // ... 
List<List<ElementWithIndices<E>>> listWithIndices = convert(list); 
Collections.sort(listWithIndices, myComparator); // compare on the Es 
// listWithIndices now contains the sorted elements with their original indices 
+0

感谢您的回复,但这个概念对我来说是新的,你可以举一个简单的例子来说明如何使用这个概念谢谢 – 2015-02-11 22:39:15

1

你可以做的是创建一个包含指针数据单独的索引结构(在此案例索引),并对索引结构进行排序。原始数据将保持不变。

这里是和示例

public static void main(String[] args) { 
    double[] data = new double[]{123.123, 345.345, -5, 10, -123.4}; 
    ArrayList<Integer> index = new ArrayList<>(data.length); 
    for(int i = 0; i<data.length; i++) { 
     index.add(i); 
    } 
    Collections.sort(index, new Comparator<Integer>() { 

     @Override 
     public int compare(Integer o1, Integer o2) { 
      return Double.compare(data[o1], data[o2]); 
      //notice that we are comparing elements of the array *data*, 
      //but we are swapping inside array *index* 
     } 
    }); 
    for(int i = 0; i<index.size(); i++) { 
     System.out.println(data[index.get(i)]); 
    } 
} 

所以,你得到排序的数据,并得到保持原有指标。

性能方面,由于大量的内存跳跃,这对于小型元件来说在CPU级别上效率不高。你最好创建一个对(index,data_element),然后对整个对进行排序。

当我们排序的对象是大对象时,它是有效的。