zoukankan      html  css  js  c++  java
  • Java-BubbleSort

    前言

        我们都知道BubbleSort这种排序算法不管从大到小排序,还是从小到大排序,都是相邻的两个进行比较,然后不符合条件时交换顺序。下面来看看引用类型是怎么进行BubbleSort的。

    内容

    • 需求:对下面几个日期进行BubbleSort排序;
    • 用到的知识:数组为引用类型、排序过程中用到Compare()方法、重写了toString()方法;

    内存分析

     

    Demo

    /*
    	作者:周丽同
    	说明:对引用类型(Date)进行BubbleSort
    */
    public class TestDateSort{
    	public static void main(String[] args){
    		Date[] days = new Date[5];//定义一个日期数组 
    		day[0] = new Date(2006,5,4);
    		day[1] = new Date(2006,7,4);
    		day[2] = new Date(2008,5,4);
    		day[3] = new Date(2004,5,9);
    		day[4] = new Date(2004,5,4);
    		
    		bubbleSort(days);
    		
    		//循环输出排序结果;
    		for(int i=0; i<days.length; i++){
    			System.out.printIn(days[i]);
    		}
    	}
    	
    	//定义一个返回值为引用类型(数组)的bubbleSort方法;
    	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;
    	}
    }
    
    class Date{
    	int year,month,day;
    	
    	//Date构造方法
    	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;
    	}
    	
    	//重写了toString方法
    	public String toString(){
    		return "Year:Month:Day --" + year + "-" + month + "-" + day;
    	}
    }

    感谢您的宝贵时间······

  • 相关阅读:
    洛谷题单 算法1-1 模拟和高精度
    第十一届蓝桥杯 b组
    jdk的安装、java环境配置
    哈夫曼树 java
    机器学习基石8-Noise and Error
    Java基础12-工具类;变长参数;IO
    机器学习基石7-The VC Dimension
    Java基础11-List;Set;Map
    Java基础10-集合
    机器学习基石6-泛化理论
  • 原文地址:https://www.cnblogs.com/zhoulitong/p/6412366.html
Copyright © 2011-2022 走看看