• 用冒泡排序对Date类数组排序


    public class TestDateSort {
    
        public static void main(String[] args) {
            Date[] days = new Date[5];
            days[0] = new Date(2016, 5, 1);
            days[1] = new Date(2016, 7, 1);
            days[2] = new Date(2018, 5, 4);
            days[3] = new Date(2014, 5, 9);
            days[4] = new Date(2014, 5, 4);
            
            System.out.println("排序前: ");
            for(int i=0; i<days.length; i++) {
                System.out.println(days[i]);
            }
            
            bubbleSort(days);    //调用冒泡排序
            
            System.out.println("排序后: ");
            for(int i=0; i<days.length; i++) {
                System.out.println(days[i]);
            }
            
        }
    
        //冒泡排序Date[]
        private static void bubbleSort(Date[] days) {
            int len = days.length-1;    //定义len为数组长度减一
            
            for(int i = len; i > 0; --i ) {
                for(int j = 0; j < i; ++j) {
                    if(days[j].compare(days[j+1])>0) { 
                        Date temp = days[j];
                        days[j] = days[j+1];
                        days[j+1] = temp;
                    }
                }
            }        
        }
        
    }
    
    //定义一个Date类
    class Date{
        int year, month, day;
        
        //构造方法
        Date(int year, int month,int day){
            this.year = year;
            this.month = month;
            this.day = day;
        }
        
        //按年、月、日比较Date的方法
        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()方法,按照重写的方式输出
        @Override
        public String toString() {
            return "Year:Month:Day -- " + year + "-" + month + "-" + day;
        }
            
    }

     输出结果:

    排序前:
    Year:Month:Day -- 2016-5-1
    Year:Month:Day -- 2016-7-1
    Year:Month:Day -- 2018-5-4
    Year:Month:Day -- 2014-5-9
    Year:Month:Day -- 2014-5-4
    排序后:
    Year:Month:Day -- 2014-5-4
    Year:Month:Day -- 2014-5-9
    Year:Month:Day -- 2016-5-1
    Year:Month:Day -- 2016-7-1
    Year:Month:Day -- 2018-5-4

  • 相关阅读:
    beginAppearanceTransition
    runtime基础
    UIStoryboard跳转界面
    xcode所有版本下载地址
    UIImage添加滤镜
    苹果copy等其他的英文改成中文
    UITextField输入中文
    keyboard添加down按钮
    2020-07-08:mysql只有一个表a,什么情况下会造成死锁,解决办法是什么?
    2020-07-05:tcp和udp的区别和应用场景。如何实现断点续传?
  • 原文地址:https://www.cnblogs.com/pangxiaoshuai/p/10806989.html
Copyright © 2020-2023  润新知