给出一组年龄,用冒泡排序求最大年龄,最小年龄

法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//求出最大年龄,求出最小年龄,求出平均年龄
int[] ages = {34,11,45,23,16};
boolean flag = true ;
for (int i = 4; flag && i >0 ; i--) {
flag = false ;
for (int j = 0; j < i; j++) {
if(ages[j]>ages[j+1]){
int temp = ages[j];
ages[j] = ages[j+1];
ages[j+1] = temp ;
flag = true ;
}
}
System.out.println("-------");
}
for (int i = 0; i < 5; i++) {
System.out.print(ages[i]+ "\t");
}

法二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int[] ages = {1,2,3,4,5};
boolean flag = true ;
for (int i = 0; flag && i < ages.length-1; i++) {
flag = false ;
for (int j = 0; j < ages.length - i - 1; j++) {
if(ages[j] > ages[j+1]){
int temp = ages[j];
ages[j] = ages[j+1];
ages[j+1] = temp ;
flag = true ;
}

}
System.out.println("-----");
}

for (int i = 0; i < ages.length; i++) {
System.out.print(ages[i]+"\t");
}
0%