java bubble sort_Java-BubbleSort

前言

我们都知道BubbleSort这种排序算法不管从大到小排序,还是从小到大排序,都是相邻的两个进行比较,然后不符合条件时交换顺序。下面来看看引用类型是怎么进行BubbleSort的。

内容

需求:对下面几个日期进行BubbleSort排序;

用到的知识:数组为引用类型、排序过程中用到Compare()方法、重写了toString()方法;

内存分析

deebfe77a5f9c421727e95ea003cee19.png

Demo

/*

作者:周丽同

说明:对引用类型(Date)进行BubbleSort

*/

public class TestDateSort{

public static void main(String[] args){

Date[] days = new Date[5];//定义一个日期数组

day[0] = new Date(2006,5,4);

day[1] = new Date(2006,7,4);

day[2] = new Date(2008,5,4);

day[3] = new Date(2004,5,9);

day[4] = new Date(2004,5,4);

bubbleSort(days);

//循环输出排序结果;

for(int i=0; i

System.out.printIn(days[i]);

}

}

//定义一个返回值为引用类型(数组)的bubbleSort方法;

public static Date[] bubbleSort(Date[] a){

int len = a.length;

for(int i =len-1;i>=1;i--){

for(int j =0;j<=i-1;j++){

if (a[j].compare(a[j+1]) > 0){

Date temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}

}

}

return a;

}

}

class Date{

int year,month,day;

//Date构造方法

Date(int y,int m,int d){

year = y;

month = m;

day = d;

}

//定义了一个比较算法(采用递归方式);

public int compare(Date date){

return year > date.year ? 1

: year < date.year ? -1

: month > date.month ? 1

: month < date.month ? -1

: day > date.day ? 1

: day < date.day ? -1 : 0;

}

//重写了toString方法

public String toString(){

return "Year:Month:Day --" + year + "-" + month + "-" + day;

}

}

感谢您的宝贵时间······

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值