冒泡排序示例

该博客展示了一个Java编程示例,创建了一个图书类,包含书名、价格和作者属性。博主通过创建一个Book对象列表并填充数据,然后使用冒泡排序算法按价格从小到大对图书进行排序,并将排序前后的结果打印到控制台。示例中详细展示了Book类的定义、冒泡排序的实现以及对象的toString方法。
摘要由CSDN通过智能技术生成

题目要求:

创建一个图书类,里面有书名,价格,作者属性,乱序添加几本图书,最后按照书本价格从小到大的顺序冒泡排序打印在控制台

代码实现

public class ListTest {
    public static void main(String[] args) {
        
        List list = new ArrayList();

        list.add(new book("水浒传1",99,"施耐庵"));
        list.add(new book("水浒传2",9,"施耐庵"));
        list.add(new book("水浒传3",9999,"施耐庵"));
        list.add(new book("水浒传4",999,"施耐庵"));

        for (Object o :list) {
            System.out.println(o);
        }
               sort(list);
        System.out.println("第二次遍历");
        for (Object o :list) {
            System.out.println(o);
        }
    }

    //冒泡排序
   public static void sort(List list){
       int size = list.size();
       for(int i=0;i<size-1;i++){
           for(int j=0;j<size-1-i;j++){
               book b1 = (book)list.get(j);
               book b2 = (book) list.get(j+1);
               if(b1.getPrice() > b2.getPrice()){
                   list.set(j,b2);
                   list.set(j+1,b1);
               }
           }

       }

    }
}
class book{
    private String name;
    private int price;
    private String author;

    public book(String name, int price, String author) {
        this.name = name;
        this.price = price;
        this.author = author;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", author='" + author + '\'' +
                '}';
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值