2015-04-07 145 views
1

排序阵列柱像我想在这里做的是我的最后一排我的值进行排序,并根据对其他colums是排序数可能在同一行中也改变排序二维数组3列

例如

int[][] array= { {1, 5, 3},{2, 6, 4},{12, 10, 1},{30, 75, 1} };

和输出应该是

{12, 10, 1} {30, 75, 1} {1, 5, 3} {2, 6, 4}

`System.out.println(“Entre la cantidad de procesos que quiere correr:”); int pros = scan.nextInt();

   int[][] myArr = new int[pros][3]; 

       for(int i=0; i< pros; i++){ 


        System.out.println("CPU Burst proceso "+count+" :"); 
        time2=scan.nextInt(); 

        System.out.println("Arrival Time proceso "+count+" :"); 
         arrt=scan.nextInt(); 


         myArr[i][0]=count; 
         myArr[i][1]=time2; 
         myArr[i][2]=arrt; 


       count++; 
       } 


       Arrays.sort(myArr, new Comparator<int[]>() { 
        public int compare(int[] o1, int[] o2) { 
         return Integer.compare(o2[2], o1[2]); 
        } 
       }); 



       System.out.println(Arrays.deepToString(myArr)); ` 
+5

你能分享你已经尝试到现在什么。你至少需要中途到达,以便我们能够帮助你。 – Panther

+0

我发现,但我试图实施,但没有工作\t \t \t \t \t myArr.sort(function(a,b){return a [2] - b [2]; \t}); –

+0

可以请你帮我分类算法,你想要的。根据你的输入和输出,我不能排除任何逻辑 –

回答

-1

让我们构造一个辅助数组,其长度是一样的array.length

int[] thirdColumnValues = new int[array.length]; 

然后,我们可以复制第三列的值:

for(int i = 0; i < array.length; i++) { 
    thirdColumnValues[i] = array[i][2]; 
} 

然后我们就可以解决这辅助阵列:

Arrays.sort(thirdColumnValues); 

然后我们就可以存储分类值放回原数组:

for(int i = 0; i < array.length; i++) { 
    array[i][2] = thirdColumnValues[i]; 
} 
+0

bu我的数组是2d并且可以在3列上排序 –

+0

Oops ..误解了你的问题! –

1

您可以使用自定义Comparator由第三个元素的数组进行比较。

我们可以使用下面的比较:

(a1, a2) -> Integer.compare(a1[2], a2[2]) 

接受两个数组作为参数和返回Integer.compare()对他们的第三个要素的结果。

例如:

int[][] array = {{1, 5, 3}, {2, 6, 4}, {12, 10, 1}, {30, 75, 1}}; 
Arrays.sort(array, (a1, a2) -> Integer.compare(a1[2], a2[2])); 
System.out.println(Arrays.deepToString(array)); 

输出:

[[12, 10, 1], [30, 75, 1], [1, 5, 3], [2, 6, 4]] 
+0

a1或a2是什么? –

+0

@IfrahimHernandez只是表示我们正在比较的两个“int []'数组的变量。 –

+0

我从哪里得到比较器 –