[英]multidimensional array sorting by column in java
i need some help in this problem, there are three columns namely phase#, block# and lot#, i needed to sort the phase# in ascending order while the other two will be sorted accordingly to its phase#: 我需要此问题的帮助,共有三列,分别是phase#,block#和lot#,我需要按升序对phase#进行排序,而其他两列将根据其phase#进行相应排序:
Problem: 问题:
Phase# 1-2-1-3-1-2-1 阶段1-2-1-3-1-2-1
Block# 1-1-2-1-2-1-1 编号1-1-2-1-2-1-1
Lot# 1-2-2-2-3-1-1 编号1-2-2-2-3-1-1
What it should be like: 它应该是什么样的:
Phase# 1-1-1-1-2-2-3 阶段1-1-1-1-2-2-3
Block# 1-2-2-1-1-1-1 区块#1-2-2-1-1-1
Lot# 1-2-3-1-2-1-2 第1-2-3-1-1-2号
here's what I've got so far: 这是到目前为止我得到的:
import java.io.*;
import java.util.*;
public class test{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x = 7;
int y = 3;
int[][] phase= new int[x][y];
int swap = 0, temp, i, min = 0;
phase[0][0] = 1;
phase[1][0] = 2;
phase[2][0] = 1;
phase[3][0] = 3;
phase[4][0] = 1;
phase[5][0] = 2;
phase[6][0] = 1;
phase[0][1] = 1;
phase[1][1] = 1;
phase[2][1] = 2;
phase[3][1] = 1;
phase[4][1] = 2;
phase[5][1] = 1;
phase[6][1] = 1;
phase[0][2] = 2;
phase[1][2] = 2;
phase[2][2] = 2;
phase[3][2] = 2;
phase[4][2] = 3;
phase[5][2] = 1;
phase[6][2] = 1;
System.out.println("UNSORTED: \n");
System.out.println("Phase#\tBlock#\tLot#");
for(i = 0; i < phase.length; i++){
System.out.print(phase[i][0] + "\t" + phase[i][1] + "\t"+phase[i][2]);
System.out.print("\n");
}
System.out.println("\nSORTED:\n");
for(i = 0; i <= phase.length- 1; i++){
min = i;
for(int a = i+1; a < phase.length; a++ ){
if(phase[a][0]<phase[a][0]){
temp=phase[i][0];
phase[i][0]=phase[a][0];
phase[a][0]=temp;
}
}
}
System.out.println("Phase#\tBlock#\tLot#");
for(int j = 0; j < phase.length; j++){
System.out.print(phase[j][0] + "\t" + phase[j][1] + "\t"+phase[j][2]);
System.out.print("\n");
}
}
} }
将Comparator接口实现为(向左int [],向右int [])->向左[0]-向右[0],并将其传递给Arrays.sort()方法:
Arrays.sort(phase, (int [] left, int[] right) -> left[0]-right[0]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.