当前位置:网站首页>冒泡排序及优化
冒泡排序及优化
2022-04-22 07:50:00 【星空下的那个人影】
普通冒泡排序(以升序为例):
- 依此比较数组中相邻两个元素大小,若a[j]>a[j+1],则交换两个元素,两两都比较一遍称为一轮冒泡,结果是让最大的元素排至最后
- 重复以上步骤,直到整个数组有序
import java.util.Arrays;
public class Task01_BobbleSort {
public static void main(String[] args) {
int[] a = {
5, 9, 7, 4, 1, 3, 2, 8};
// int[] a = {1, 2, 3, 4, 5, 6, 7, 8};
bubble(a);
}
public static void bubble(int[] a) {
for (int j = 0;j < a.length-1;j++) {
// 一轮冒泡
for (int i = 0; i < a.length - 1 - j; i++) {
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
}
}
System.out.println("第"+j+"轮冒泡"+Arrays.toString(a));
}
}
public static void swap(int[] a,int i,int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}


优化:
- 可以设置一个标志位,记录每一次排序是否发生了交换,没有交换表示数组已经有序了
public static void bubble(int[] a) {
for (int j = 0;j < a.length-1;j++) {
// 一轮冒泡
boolean swapped = false; // 是否发生交换
for (int i = 0; i < a.length - 1 - j; i++) {
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
swapped = true;
}
}
System.out.println("第"+j+"轮冒泡"+Arrays.toString(a));
if (!swapped){
break;
}
}
}


- 记录上一次最后交换的位置,作为下一次循环的结束边界。如果最后一次交换的位置是0,说明已经排序成功,退出循环。
public static void bubble2(int[] a) {
int n = a.length - 1;
while (true) {
int last = 0; // 表示最后一次交换索引位置
for (int i = 0; i < n; i++) {
System.out.println("比较次数"+i);
if (a[i] > a[i + 1]) {
swap(a, i, i + 1);
last = i;
}
}
System.out.println(Arrays.toString(a));
n = last;
if (n == 0){
break;
}
}
}


版权声明
本文为[星空下的那个人影]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sb_jb/article/details/124285856
边栏推荐
- Redhat7 configuration yum
- Blue Bridge Cup: dance of sine [Jav language implemented recursively]
- How does CSDN reprint articles
- tar 源码包管理-源码包安装方法
- 一棵开始成长的树
- PCIe learning - Introduction to PCIe bus architecture: transaction layer - data link layer - physical layer (8)
- DTV terminology
- Operation steps for mysqlbin log playback
- 实现“ 字体逐渐展现 ”程序
- HyperLedger Explorer 0.3.9环境搭建
猜你喜欢

Matlab installation product selection, how to select the products to be installed

94. Middle order traversal of binary tree (easy)

初识C语言~循环语句

Restore MySQL service after computer reset

服务器设置自动开机及定时开机

初识C语言~分支语句

Single page application

Install_ FAILED_ MISSING_ SHARED_ LIBRARY

Cesium realizes the monomer of buildings (divided into buildings and layers)

布尔类型【bool】
随机推荐
The problems encountered in the compilation of Nacos source code are sorted out as follows
Lambda expression
NMAP高级使用技巧
工业缺陷检测项目实战(三)——基于FPN_Tensorflow的PCB缺陷检测
win系统pinpoint编译安装遇到的坑和大家分享
CSDN如何转载文章
Explain escape character
Realization of floor decomposition animation in cesium
94. Middle order traversal of binary tree (easy)
tar 源码包管理-源码包安装方法
Hyperledger Fabric1.4環境搭建及示例測試
Mapbox sets the official map language to Chinese
机器学习之概率模型
二分查找【详解】
Fabric测试示例,遇到orderer Exited(x) x seconds
Nessus漏洞扫描简介
ROM、RAM、SRAM、DRAM、Flash、SDRAM區別
winkawaks1.45如何联机?winkawaks1.45怎样联机对战(其他版本类似)
PCIe learning - how to make PCIe bus compatible with PCI bus in software (7)
Pointer and array (detailed operation)