/**
* 猴子过三关(选择排序)
*/
import java.util.Scanner;
public class Work18 {
public static void main(String[] args) {
//定义可以装五只猴子的对象数组
int size=5;
Monkey []monkeys=new Monkey[size];
Scanner sr=new Scanner(System.in);
//初始化各个猴子
for(int i=0;i
System.out.println("请输入第"+(i+1)+"只猴子的高度:");
float height=sr.nextFloat();
monkeys[i]=new Monkey((i+1)+"",height);
}
//让老猴排序
Monkey oldMonkey=new Monkey("1000", 1.2f);
//排序
oldMonkey.selectSort(monkeys);
//验证输出
oldMonkey.show(monkeys);
}
}
//猴子类
class Monkey{
private String monkeyId;
private float height;
public Monkey(String mokeyId,float height){
this.monkeyId=mokeyId;
this.height=height;
}
//选择排序(用外循环做为下标交换)
public void selectSort(Monkey []monkeys){
float tempHeight=0f;
String tempId="";
for(int i=0;i
//认为下标为i的猴子身高是最低的
float minHeight=monkeys[i].height;
int minIndex=i;
//和后面猴子比较
for(int j=i+1;j
if(minHeight>monkeys[j].height){
//修正最低值
minHeight=monkeys[j].height;
minIndex=j;
}
if(minIndex!=i){
//交换
tempHeight=monkeys[minIndex].height;
monkeys[minIndex].height=monkeys[i].height;
monkeys[i].height=tempHeight;
tempId=monkeys[minIndex].monkeyId;
monkeys[minIndex].monkeyId=monkeys[i].monkeyId;
monkeys[i].monkeyId=tempId;
}
}
}
}
//显示队列
public void show(Monkey []monkeys){
for(int i=0;i
System.out.println("猴子编号:"+monkeys[i].monkeyId+"身高:"+monkeys[i].height);
}
}
}
sr=
x
1/**
2* 猴子过三关(选择排序)
3*/
4import java.util.Scanner;
5public class Work18 {
6public static void main(String[] args) {
7//定义可以装五只猴子的对象数组
8int size=5;
9Monkey []monkeys=new Monkey[size];
10Scanner sr=new Scanner(System.in);
11//初始化各个猴子
12for(int i=0;i
13System.out.println("请输入第"+(i+1)+"只猴子的高度:");
14float height=sr.nextFloat();
15monkeys[i]=new Monkey((i+1)+"",height);
16}
17//让老猴排序
18Monkey oldMonkey=new Monkey("1000", 1.2f);
19//排序
20oldMonkey.selectSort(monkeys);
21//验证输出
22oldMonkey.show(monkeys);
23}
24}
25
26//猴子类
27class Monkey{
28private String monkeyId;
29private float height;
30public Monkey(String mokeyId,float height){
31this.monkeyId=mokeyId;
32this.height=height;
33}
34
35//选择排序(用外循环做为下标交换)
36public void selectSort(Monkey []monkeys){
37float tempHeight=0f;
38String tempId="";
39for(int i=0;i
40//认为下标为i的猴子身高是最低的
41float minHeight=monkeys[i].height;
42int minIndex=i;
43//和后面猴子比较
44for(int j=i+1;j
45if(minHeight>monkeys[j].height){
46//修正最低值
47minHeight=monkeys[j].height;
48minIndex=j;
49}
50if(minIndex!=i){
51//交换
52tempHeight=monkeys[minIndex].height;
53monkeys[minIndex].height=monkeys[i].height;
54monkeys[i].height=tempHeight;
55
56tempId=monkeys[minIndex].monkeyId;
57monkeys[minIndex].monkeyId=monkeys[i].monkeyId;
58monkeys[i].monkeyId=tempId;
59}
60}
61}
62}
63
64//显示队列
65public void show(Monkey []monkeys){
66for(int i=0;i
67System.out.println("猴子编号:"+monkeys[i].monkeyId+"身高:"+monkeys[i].height);
68}
69}
70}