1 /**//* 2 * 将一些日期散乱存入数组, 3 * 然后用冒泡法升序排列 4 * 并查找一个存在的日期,给出该日期所在数组中的位置 5 */ 6 public class TestDateSort { 7 public static void main(String[] args) { 8 Date[] days = new Date[5]; 9 days[0] = new Date(2006, 5, 4); 10 days[1] = new Date(2006, 7, 4); 11 days[2] = new Date(2008, 5, 4); 12 days[3] = new Date(2004, 5, 9); 13 days[4] = new Date(2004, 5, 4); 14 15 Date d = new Date(2006, 7, 4); 16 17 bubbleSort(days); 18 19 for(int i=0; i<days.length; i++) { 20 System.out.println(days[i]); 21 } 22 23 System.out.println(binarySearch(days, d)); 24 } 25 26 public static Date[] bubbleSort(Date[] a) { 27 int len = a.length; 28 for(int i = len-1;i>=1;i--) { 29 for(int j = 0;j<=i-1;j++) { 30 if(a[j].compare(a[j+1]) > 0) { 31 Date temp = a[j]; 32 a[j]=a[j+1]; 33 a[j+1]=temp; 34 } 35 } 36 } 37 return a; 38 } 39 40 public static int binarySearch(Date[] days, Date d) { 41 if (days.length==0) return -1; 42 43 int startPos = 0; 44 int endPos = days.length-1; 45 int m = (startPos + endPos) / 2; 46 while(startPos <= endPos) { 47 if(d.compare(days[m]) == 0) return m; 48 if(d.compare(days[m]) > 0) { 49 startPos = m + 1; 50 } 51 if(d.compare(days[m]) < 0) { 52 endPos = m -1; 53 } 54 m = (startPos + endPos) / 2; 55 } 56 return -1; 57 } 58 } 59 60 class Date { 61 int year, month, day; 62 63 Date(int y, int m, int d) { 64 year = y; month = m; day = d; 65 } 66 67 public int compare(Date date) { 68 return year > date.year ? 1 69 : year < date.year ? -1 70 : month > date.month ? 1 71 : month < date.month ? -1 72 : day > date.day ? 1 73 : day < date.day ? -1 : 0; 74 } 75 76 public String toString() { 77 return "Year:Month:Day -- " + year + "-" + month + "-" + day; 78 } 79 }
|
|
|
| 日 | 一 | 二 | 三 | 四 | 五 | 六 |
---|
29 | 30 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|
导航
统计
留言簿
文章档案(10)
搜索
最新评论

|
|