冒泡排序算法原理及JAVA实现

本文介绍了Java实现的冒泡排序算法,包括其基本原理、复杂度分析及源代码实现。通过实例展示了如何使用Date类进行日期排序,详细解释了算法的工作流程和效率特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

冒泡排序法:关键字较小的记录好比气泡逐趟上浮,关键字较大的记录好比石块下沉,每趟有一块最大的石块沉底。

算法本质:(最大值是关键点,肯定放到最后了,如此循环)每次都从第一位向后滚动比较,使最大值沉底,最小值上升一次,最后一位向前推进(即最后一位刚确定的最大值不再参加比较,比较次数减1)


复杂度 : 时间复杂度  O (n2) ,空间复杂度 O (1)

JAVA源代码(成功运行,需要Date类)

[java]  view plain copy print ?
  1.     public static void bubbleSort(Date[] days) {  
  2.         int len = days.length;  
  3.         Date temp;  
  4.         for (int i = len - 1; i >= 1; i--) {  
  5.             for (int j = 0; j < i; j++) {  
  6.                 if (days[j].compare(days[j + 1]) > 0) {  
  7.                     temp = days[j + 1];  
  8.                     days[j + 1] = days[j];  
  9.                     days[j] = temp;  
  10.                 }  
  11.             }  
  12.         }  
  13.     }  
  14. class Date {  
  15.     int year, month, day;  
  16.   
  17.     Date(int y, int m, int d) {  
  18.         year = y;  
  19.         month = m;  
  20.         day = d;  
  21.     }  
  22.   
  23.     public int compare(Date date) {  
  24.         return year > date.year ? 1 : year < date.year ? -1  
  25.                 : month > date.month ? 1 : month < date.month ? -1  
  26.                         : day > date.day ? 1 : day < date.day ? -1 : 0;  
  27.     }  
  28.   
  29.     public void print() {  
  30.         System.out.println(year + " " + month + " " + day);  
  31.     }  
  32. }  

[java]  view plain copy print ?
  1. package testSortAlgorithm;  
  2.   
  3. public class BubbleSort {  
  4.     public static void main(String[] args) {  
  5.         int array[] = { 56842490 };  
  6.         bubbleSort(array);  
  7.         for (int i = 0; i < array.length; i++) {  
  8.             System.out.println(array[i]);  
  9.         }  
  10.     }  
  11.   
  12.     public static void bubbleSort(int array[]) {  
  13.         int temp;  
  14.         for (int i = array.length - 1; i > 0; i--) {  
  15.             for (int j = 0; j < i; j++) {  
  16.                 if (array[j] > array[j + 1]) {  
  17.                     temp = array[j];  
  18.                     array[j] = array[j + 1];  
  19.                     array[j + 1] = temp;  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  
转载于:http://blog.youkuaiyun.com/xuxurui007/article/details/7640490




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值