冒泡排序
class Person{
double height;
Person(double h){
height = h;
}
}
public class Sort {
public static void main(String[] args) {
//十个不同身高的对象放在数组中
Person [] p = {new Person(1.2),new Person(1.0),new Person(1.5),new Person(1.1),new Person(1.7),new Person(1.3),new Person(1.4),new Person(2.0),new Person(1.8),new Person(1.9)};
//根据身高进行高矮排序
for(int i = 0;i<p.length;i++){
for(int j = 0;j<i;j++){
if(p[i].height<p[j].height){
Person temp = p [i];
p[i] = p[j];
p[j] = temp;
}
}
System.out.print(p[i].height+" ");
}
}
} 为什么输出结果有重复呢 求解
------解决方案--------------------------------------------------------
逻辑搞清楚!!
------解决方案--------------------------------------------------------
试试
- Java code
class Person{double height;Person(double h){height = h;}}public class Sort {public static void main(String[] args) {//十个不同身高的对象放在数组中Person [] p = {new Person(1.2),new Person(1.0),new Person(1.5),new Person(1.1),new Person(1.7),new Person(1.3),new Person(1.4),new Person(2.0),new Person(1.8),new Person(1.9)};//根据身高进行高矮排序for(int i = 0;i<p.length;i++){for(int j = 0;j<p.length-i-1;j++){if(p[j].height>p[j+1].height){Person temp = p [j];p[j] = p[j+1];p[j+1] = temp;}}System.out.print(p[i].height+" ");}}}
------解决方案--------------------------------------------------------
你可以在纸上画一下你的循环根本不能实现排序呀
------解决方案--------------------------------------------------------
循环还是多在纸上画画,不要总是都用脑子去记忆