创建对象数组:
public class Test
{
public static void main(String[] args)
{
//申明Date类型数组
Date[] stu = {
new Date(2006, 1, 22),
new Date(2006, 7, 4),
new Date(2008, 5, 28),
new Date(2004, 6, 9),
new Date(2004, 5, 6),
new Date(2006, 7, 12),
new Date(2002, 8, 4),
new Date(2014, 9, 9),
new Date(2000, 12, 18),
new Date(2003, 11, 22),
new Date(2005, 3, 9),
new Date(2007, 2, 14)
};
//排序前
System.out.println("排序前");
for (int i = 0; i < stu.length; i++)
{
System.out.println(stu[i]);
}
bubbleSort(stu);//冒泡排序
//排序后
System.out.println("排序后");
for (int i = 0; i < stu.length; i++)
{
System.out.println(stu[i]);
}
System.out.println("序号:"+ find(stu, new Date(2006, 7, 12)));//查找
}
static Date[] bubbleSort(Date[] arr)//这个地方返回 数组Date[],注意java是可以返回数组的
{
Date tmp;
for (int i = arr.length-1; i >= 1; i--)//这里采用冒泡排序
{
for (int j = 0; j <= i - 1; j++)
{
if(arr[i].compere(arr[j]) < 0)//这里直接调用了Date类中的compare方法;
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return arr;//返回的为数组类型
}
public static int find(Date[] arr,Date m)//二分法查找
{
int index = -1;
if(arr.length == 0)
return index;
//二分法查找
int left = 0;
int right = arr.length - 1;
int mid = (left + right) / 2;
while(left <= right)
{
if(arr[mid].compere(m) > 0)
{
right = mid -1;
}
else if(arr[mid].compere(m) < 0){
left = mid + 1;
}
else {
index = mid;
break;
}
mid = (left + right) / 2;
}
return index;
}
}
class Date
{
int year;
int month;
int day;
public Date(int year, int month, int day) //构造方法
{
this.year = year;
this.month = month;
this.day = day;
}
public int compere(Date 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() //重写toString()方法
{
return ("Year:Month:Day--" + year + "-" + month + "-" + day);
}
}