码迷,mamicode.com
首页 > 编程语言 > 详细

引用类型参数的冒泡排序方法 例子

时间:2015-07-03 18:53:05      阅读:89      评论:0      收藏:0      [点我收藏+]

标签:

import java.util.Arrays;
class TestSortUtil {
    
    public static void main(String[] args) {
        Student[] stu={
                new Student("凯文",15,101),
                new Student("Mike",16,103),
                new Student("John",14,102),
                new Student("Sara",15,104),
                new Student("MJ",16,106),
                new Student("JK",14,105)
        };
        System.out.println("排序前:");
        System.out.println(Arrays.toString(stu));
        ObjectSort.bubblesort(stu);
        
        System.out.println("排序后:");
        System.out.println(Arrays.toString(stu));
    }    
}
 class Student implements ToCompares{
    private String name;
    private int age;
    private int schoolNum;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public int getSchoolNum() {
        return schoolNum;
    }
    public void setSchoolNum(int schoolNum) {
        this.schoolNum = schoolNum;
    }
    public Student(String name, int age, int schoolNum) {
        super();
        this.name = name;
        this.age = age;
        this.schoolNum = schoolNum;
    }
    public Student() {
        super();
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + ", schoolNum="
                + schoolNum + "]";
    }
    @Override
    public int compareTo(Object obj) {
        Student stu=(Student)obj;
        return this.schoolNum-stu.schoolNum;
    }    
}
class ObjectSort {
    public static void bubblesort(Object[] obj){
        for (int i = 0; i < obj.length-1; i++) {
            boolean flag=true;//用来标记经过一次排列后是否有序,若有序了则为true
            for (int j = 0; j < obj.length-1-i; j++) {
                ToCompares a=(ToCompares)obj[j];
                ToCompares b=(ToCompares)obj[j+1];
                if (a.compareTo(b)>0) {
                    swap(obj,j,j+1);
                    flag=false;//当满足条件时,表面数组无序,叫标记改为false;
                }
            }    
            if (flag) {
                    break;//当flag为true的时候,表示数组从未发生过交换 即:已经有序 无须继续进行其他外层循环,提高效率
                }
        }
    }
    public static void swap(Object[] obj,int a,int b){
        Object temp;
        temp=obj[a];
        obj[a]=obj[b];
        obj[b]=temp;
    }
}
interface ToCompares {
    //定义一个用来比较两个对象成员相比较后返回值的方法。重写后可以用两个对象属性相比较后的大小来比较。
    public int compareTo(Object obj);
}

 

引用类型参数的冒泡排序方法 例子

标签:

原文地址:http://www.cnblogs.com/bingzhikun/p/4619211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!