1. 给定一组数,求最大的3个数
public static void getTopMaxN(int [] a){
for (int i = a.length-1; i >0; i--) {
for (int j = 0; j < i; j++) {
if(a[i]<a[j]){
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
if(i == a.length-3){
System.out.println(a[a.length-1]);
System.out.println(a[a.length-2]);
System.out.println(a[a.length-3]);
return;
}
}
}
2. 给定一组数,求最小的3个数
public static void getTopMinN(int []a){
for (int i = 0; i < a.length-1; i++) {
for (int j = a.length-1; j > i ; j--) {
if(a[i] > a[j]){
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
if(i == 2){
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
return;
}
}
}
3. 测试
public static void main(String[] args) {
int [] a = new int[]{0,1,9,5,10,2,90,43,1,89,23,45};
getTopMaxN(a);
getTopMinN(a);
}