请帮助我获取代码以排列从最低到最高的输入值。以下是我的示例代码:
System.out.print("Enter Number of Process: ");
int p = Integer.parseInt(input.readLine());
int [] arrival = new int[p];
int [] size = new int[p];
for(int i=0;i<p;i++){
System.out.print("Arrival Time of Process #"+(i+1)+":");
arrival[i]=Integer.parseInt(input.readLine());
预期输出必须是:
输入流程数:4
流程#1:100的到达时间 过程#2的到达时间:110
流程#3:102的到达时间 过程到货时间#4:101
P1:100
P4:101
P3:103
P2:110
如果您对First Come First Serve Algorithm
很熟悉,那就与此有关。
答案 0 :(得分:0)
您可以使用方法Arrays.sort(array []);
System.out.print("Enter Number of Process: ");
int p = Integer.parseIntln(input.readLine());
int [] arrival = new int[p];
int [] size = new int[p];
for(int i=0;i<p;i++) {
System.out.println("Arrival Time of Process #"+(i+1)+":");
arrival[i]=Integer.parseInt(input.readLine());
}
//You can make a copy of arrival[] and then sort it.
//So arrival[] won't be sorted.
size = arrival.clone();
size = Arrays.sort(size);
for(int i = 0; i < p; i++) {
System.out.println("P"+(i+1)+": "+size[i]);
}
答案 1 :(得分:0)
使用Arrays.sort
。
int[] is = {100, 110, 101, 102};
Arrays.sort(is);
for (int i : is) {
System.out.println(i);
}
输出:
100
101
102
110
答案 2 :(得分:0)
我看起来你也想在进行排序时跟踪输入值的原始索引。我建议你阅读的主题是sorting pairs of (value, index) compared by value。请尝试以下方法:
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Number of Process: ");
int p = 0;
try {
p = Integer.parseInt(br.readLine());
} catch (NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
Pair[] arrival = new Pair[p];
for (int i = 0; i < p; i++) {
System.out.print("Arrival Time of Process #" + (i + 1) + ":");
try {
arrival[i] = new Pair(i + 1, Integer.parseInt(br.readLine()));
} catch (NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
Arrays.sort(arrival);
for (int i = 0; i < arrival.length; i++) {
System.out.println("P" + arrival[i].index + ": " + arrival[i].value);
}
}
// a little change was made to the original code
public static class Pair implements Comparable<Pair> {
public final int index;
public final int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
return Integer.valueOf(this.value).compareTo(other.value);
}
}
输出是:
Enter Number of Process: 4
Arrival Time of Process #1:100
Arrival Time of Process #2:110
Arrival Time of Process #3:103
Arrival Time of Process #4:101
P1: 100
P4: 101
P3: 103
P2: 110