Java数据结构及算法实例:冒泡排序 Bubble Sort
作者:junjie 时间:2022-10-17 08:39:45
/**
* 冒泡排序估计是每本算法书籍都会提到的排序方法。
* 它的基本思路是对长度为N的序列,用N趟来将其排成有序序列。
* 第1趟将最大的元素排在序列尾部,第2趟将第2大的元素排在倒数第二的位置,
* 即每次把未排好的最大元素冒泡到序列最后端。
* 该排序方法实际上分为两重循环,外层循环:待排元素从数组的第1个元素开始。
* 内层循环:待排元素从数组的第1个元素开始,直到数组尾端未排过的元素。
* 在内循环中,如果遇到前面元素比其后的元素大就交换这两个元素的位置。
* 由此可见冒泡排序的复杂度是O(n^2)
*/
package al;
public class BubbleSort {
/*
* 冒泡排序 Java语言编写,可以直接运行 输入:n个数<a1,a2,,an>
* 输出:输入序列的一个排列<a1',a2',,an'>,其中a1'<=a2'<=<=an' 待排的数也称为key 复杂度:O(n^2) 输出结果:9
* 10 14 14 21 43 50 77 例子:高矮个站队
*/
public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort();
int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };
// sort the array
bubbleSort.sort(elements);
// print the sorted array
for (int i = 0; i < elements.length; i++) {
System.out.print(elements[i]);
System.out.print(" ");
}
}
/**
* @author
* @param array
* 待排数组
* @return void
*/
public void sort(int[] array) {
int i, j;
int tmp;
for (i = 0; i <= (array.length - 1); i++) { // outer loop
for (j = 0; j < (array.length - 1 - i); j++) { // inner loop
if (array[j] > array[j + 1]) {
tmp = array[j];
array[j] = array[j + 1];
array[j + 1] = tmp;
}
}
}
}
}
标签:Java,数据结构,算法,冒泡排序,Bubble,Sort
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java实现LRU缓存淘汰算法的方法
2022-10-09 00:09:05
在Winform和WPF中注册全局快捷键实现思路及代码
2023-03-13 23:00:25
android开发去除标题栏的方法
2021-06-30 19:11:29
![](https://img.aspxhome.com/file/2023/0/109170_0s.png)
Android入门之画图详解
2023-11-09 11:47:47
![](https://img.aspxhome.com/file/2023/4/93264_0s.jpg)
Java基础知识之Java语言概述
2023-11-28 04:36:35
![](https://img.aspxhome.com/file/2023/0/60080_0s.jpg)
Spring源码解析 Bean属性填充
2021-06-28 19:17:16
![](https://img.aspxhome.com/file/2023/2/61612_0s.png)
Java类成员访问权限控制知识总结
2021-09-12 10:36:53
![](https://img.aspxhome.com/file/2023/5/96075_0s.png)
关于Springboot数据库配置文件明文密码加密解密的问题
2023-11-25 03:29:46
关于使用Mybatisplus自带的selectById和insert方法时的一些问题
2023-11-01 14:15:42
springboot集成es详解
2021-08-21 01:13:53
Java源码解析之Iterable接口
2023-04-17 08:06:57
Java listener简介_动力节点Java学院整理
2022-12-29 10:02:48
![](https://img.aspxhome.com/file/2023/8/81308_0s.png)
mybatis foreach标签的使用详解
2023-05-07 21:12:09
![](https://img.aspxhome.com/file/2023/6/119196_0s.jpg)
Android实现QQ图片说说照片选择效果
2022-05-15 12:52:08
![](https://img.aspxhome.com/file/2023/8/138788_0s.jpg)
Java开发实现人机猜拳游戏
2023-10-17 16:01:35
![](https://img.aspxhome.com/file/2023/9/61149_0s.jpg)
C#导出数据到Excel文件的方法
2023-11-13 17:27:05
Java图形用户界面设计(Swing)的介绍
2022-08-23 03:29:37
![](https://img.aspxhome.com/file/2023/4/75654_0s.jpg)
C#实现航班预订系统
2021-12-26 02:19:37
![](https://img.aspxhome.com/file/2023/5/70445_0s.jpg)
Spring FreeMarker整合Struts2过程详解
2023-03-01 00:30:52
![](https://img.aspxhome.com/file/2023/9/62169_0s.jpg)
Android Flutter自适应瀑布流案例详解
2023-05-31 17:44:21
![](https://img.aspxhome.com/file/2023/4/139204_0s.jpg)