2015-11-29 106 views
0

我有一个问题,我应该对数组进行排序并获得数组的排序索引,我认为一些示例会比单纯描述更好地展示我的问题。所以, 我提出了几个例子:如何根据两列的值对Java中的二维数组进行排序

1-example: 
n=3 
[1, 4] row=0 
[2, 5] 
[3, 6] row=2 
output should be : 0 1 2 (explanation is below) 
2-example: 
n=5 
[8, 9] row=0 
[4, 6] row=1 
[5, 11] row=2 
[3, 4] row=3 
[4, 7] row=4 
[2, 6] row=5 
output should be : 3 5 1 4 0 2(explanation is below) 

排序标准主要是根据第二列的值,首先我应该打印的第二列的值最小的指数,在1-例如它是4和它的索引为0。如果我们在第二列中遇到与第2列中相同的值(第1行和第5行相同),那么我们应该比较第一列的相应值并首先打印较小的索引。问题的另一个更精确的例子:

n=3 
[4, 6] row=0 
[1, 6] row=1 
[2, 6] row=2 
output should be : 1 2 0 

编辑:总是有2列和n行

+1

你尝试过什么? –

+0

是的,如果你想我可以告诉你我的尝试,但在这里我描述了问题的一部分,实际的问题是略有不同,所以代码 – Humoyun

+0

每当你提供正确的“比较”功能,每个排序算法将工作。 – jeerbl

回答

0

这里是你完整的解决方案试试这个,

public class TwoDimensitnArraySort { 
public static void main(String[] args) { 
    int ary[][] = {{8, 9},{4, 6},{5, 11},{3, 4},{4, 7},{2, 6}}; 

    ArrayList<TwoDArray> list = new ArrayList<TwoDArray>(); 

    for(int i = 0;i<ary.length;i++){ 
     int k = ary[i][0]; 
     int v = ary[i][1]; 
     list.add(new TwoDArray(k, v)); 
    } 

    Collections.sort(list); 
    int index = 0; 
    for(TwoDArray element : list){ 
     for(int i = 0;i<ary.length;i++){ 
      if(element.getKey() == ary[i][0] && element.getValue() == ary[i][1]){ 
       System.out.print(i + " "); 
      } 
     } 
    } 
} 
} 

class TwoDArray implements Comparable<TwoDArray>{ 
    int key; 
    int value; 

    public TwoDArray(int key,int value) { 
     this.key = key; 
     this.value = value; 
    } 


    public int getKey() { 
     return key; 
    } 



    public void setKey(int key) { 
     this.key = key; 
    } 



    public int getValue() { 
     return value; 
    } 



    public void setValue(int value) { 
     this.value = value; 
    } 



    public int compareTo(TwoDArray o) { 
     if(o.getValue() >= this.getValue()){ 
      return -1; 
     }else if (o.getValue() < this.getValue()){ 
      return 1; 
     } 
     if(o.getValue() == this.getValue()){ 
      if(o.getKey() >= this.getKey()){ 
       return -1; 
      }else if (o.getKey() < this.getKey()){ 
       return 1; 
      } 
     } 

     return 0; 
    }; 
    @Override 
    public String toString() { 
     return this.key + ":" + this.value; 
    } 
} 
+0

感谢您花时间在问题上 – Humoyun

+0

@Humoyun耶欢迎 –

+1

“给一个男人一条鱼,你喂他一天;教一个男人去钓鱼,你给他一辈子的食物“。你刚给那个男人一条鱼。 – jeerbl

1

基本上,对于这个问题,我认为,任何排序算法是可行的。你只需要指定你的compare函数来比较两个元素。

例如,如果你想冒泡排序,你的情况,这种算法(伪来自Wikipedia拍摄):

procedure bubbleSort(A : list of sortable items) 
    n = length(A) 
    repeat 
    swapped = false 
    for i = 1 to n-1 inclusive do 
     if A[i-1] > A[i] then /* COMPARE LINE */ 
     swap(A[i-1], A[i]) 
     swapped = true 
     end if 
    end for 
    until not swapped 
end procedure 

你只需要更换的评论与COMPARE LINE与行的比较compare函数可以根据需要比较对象(基于第二个元素,如果相等,则为第一个元素)。

例如,将此行替换为if compare(A[i-1], A[i]) then

总之,只要您提供正确的compare函数,就可以使用每种排序算法。

+0

这是对的,但我也应该跟踪索引不只是价值观,我面临的主要问题是排序后我失去了索引初始位置排序 – Humoyun

相关问题