欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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

时间:2021-05-03 09:59:14|栏目:JAVA代码|点击:

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

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

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

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

复制代码 代码如下:

 public static void bubbleSort(Date[] days) {
  int len = days.length;
  Date temp;
  for (int i = len - 1; i >= 1; i--) {
   for (int j = 0; j < i; j++) {
    if (days[j].compare(days[j + 1]) > 0) {
     temp = days[j + 1];
     days[j + 1] = days[j];
     days[j] = temp;
    }
   }
  }
 }
class Date {
 int year, month, day;

 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;
 }

 public void print() {
  System.out.println(year + " " + month + " " + day);
 }
}

复制代码 代码如下:

package testSortAlgorithm;

public class BubbleSort {
 public static void main(String[] args) {
  int array[] = { 5, 6, 8, 4, 2, 4, 9, 0 };
  bubbleSort(array);
  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i]);
  }
 }

 public static void bubbleSort(int array[]) {
  int temp;
  for (int i = array.length - 1; i > 0; i--) {
   for (int j = 0; j < i; j++) {
    if (array[j] > array[j + 1]) {
     temp = array[j];
     array[j] = array[j + 1];
     array[j + 1] = temp;
    }
   }
  }
 }
}

上一篇:快速排序和分治排序介绍

栏    目:JAVA代码

下一篇:java中Scanner类的简单用法分享

本文标题:冒泡排序算法原理及JAVA实现代码

本文地址:http://www.codeinn.net/misctech/113507.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有