会员
周边
众包
新闻
博问
闪存
赞助商
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
spring学习笔记
java例程练习(引用类型数据的排序和查找)[外篇]
public class TestSort { public static void main(String[] args) { Date[] days = new Date[5]; //定义5个Date days[0] = new Date(2006, 8, 6); days[1] = new Date(2007, 4, 6); days[2] = new Date(2008, 4, 9); days[3] = new Date(2004, 4, 6); days[4] = new Date(2009, 4, 5); //要找的Date Date d = new Date(2006, 8, 6); //先冒泡排序 bubbleSort(days); //打印一下便于输出查找位置 for(int i = 0; i < days.length; i++) { System.out.println(days[i]); } //二分法查找并输出位置 System.out.println(binarySearch(days,d)); } 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; } public static int binarySearch(Date[] days, Date d) { if(days.length == 0) { return -1; } int startPos = 0; int endPos = days.length - 1; int m = (startPos + endPos) / 2; while(startPos <= endPos) { if(d.compare(days[m]) == 0) { return m; } if(d.compare(days[m]) > 0) { startPos = m + 1; } if(d.compare(days[m]) < 0) { endPos = m - 1; } m = (startPos + endPos) / 2; } return -1; } } class Date { int year; int month; int day; 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; } public String toString() { return "" + year + "-" + month + "-" + day; } }
posted on
2012-04-30 10:39
spring学习笔记
阅读(
150
) 评论(
0
)
编辑
收藏
举报
刷新页面
返回顶部
导航
博客园
首页
联系
订阅
管理
公告