So I have two assignments in Java class:
1) Sort 3 numbers in ascending order using only "three" if statements. 2) Sort 4 numbers in ascending order using only "five" if statements.
I was able to do the first one with the following code. However, I have no idea how to do the 2nd one. How do I do that with only 5 if statements??? And even the first one, I have a feeling that it is not so efficient. Any help is very much appreciated. Thank you.
// First Problem Solution
public class Assignment_1 {
public static void main(String[] args) {
int a = Integer.parseInt("12");
int b = Integer.parseInt("7");
int c = Integer.parseInt("8");
if (a<b && a<c) {
a = a;
if (b < c) {
b = b;
c=c;
}
else {
int temp =b;
b = c;
c= temp;
}
}
if (b<a && b<c) {
int temp = b;
if (a < c) {
b = a;
c = c;
}
else {
b=c;
c=a;
}
a = temp;
}
if (c<a && c<b) {
int temp = c;
if (a < b) {
b = a;
c = b;
}
else {
b = b;
c = a;
}
a = temp;
}
StdOut.println(a + " " + b + " " + c);
}
}
Aucun commentaire:
Enregistrer un commentaire