[英]multidimensional array sorting by column in java
我需要此問題的幫助,共有三列,分別是phase#,block#和lot#,我需要按升序對phase#進行排序,而其他兩列將根據其phase#進行相應排序:
問題:
階段1-2-1-3-1-2-1
編號1-1-2-1-2-1-1
編號1-2-2-2-3-1-1
它應該是什么樣的:
階段1-1-1-1-2-2-3
區塊#1-2-2-1-1-1
第1-2-3-1-1-2號
這是到目前為止我得到的:
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.