DateSort选择法、冒泡法排序

public class DateSort {
public static void main(String args[]) {
Date d[] = new Date[11];
d[0] = new Date(2011,10,28);
d[1] = new Date(2008,5,9);
d[2] = new Date(2004,4,9);
d[3] = new Date(2002,8,17);
d[4] = new Date(2004,5,9);
d[5] = new Date(2006,1,23);
d[6] = new Date(2008,8,3);
d[7] = new Date(2003,2,20);
d[8] = new Date(2005,4,9);
d[9] = new Date(2004,5,7);
d[10] = new Date(2001,12,6);

print(d);
selectionSort(d);
print(d);

}

private static void bubbleSort(Date a[]) {

Date temp;

for (int i=0; i<a.length; i++) {
for (int j=0; j<a.length-1; j++) {
if (compare(a[j],a[j+1])) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}

private static void selectionSort(Date a[]) {

Date temp;
int k;

for (int i=0; i<a.length; i++) {
k = i;
for (int j=k+1; j<a.length; j++) {
//select the smaller one;
if (compare(a[k],a[j])) {
k = j;
}
}

if (i != k) {
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
}

private static boolean compare(Date a, Date b) {

if (a.year > b.year) {
return true;
}
else if (a.year == b.year) {
if (a.month > b.month) {
return true;
}
else if (a.month == b.month) {
if (a.day > b.day) {
return true;
}
else if (a.day == b.day) {
return false;
}
}
}

return false;

}

private static void print(Date a[]) {
for (int i=0; i<a.length; i++) {
System.out.println(a[i]);
}
System.out.println();
}
}

class Date {

int year, month, day;

Date(int year,int month,int day) {
this.year = year;
this.month = month;
this.day = day;
}

public String toString() {
return (year + ", " + month + ", " + day);
}
}





posted @   asashadow  阅读(462)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示