Java--冒泡排序
2021/5/30 22:50:05
本文主要是介绍Java--冒泡排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/** * 冒泡排序 */ import java.util.Arrays; public class BubbleSort { public static void main(String[] args) { int[] values={3,1,6,2,9,0,7,4,5,8}; int temp=0; for(int i=0;i<values.length-1;i++){ boolean flag=true; //优化排序,减少不必要的比较 System.out.println("######"+"第"+(i+1)+"趟"+" "+"比较"+(values.length-i-1)+"次"); for(int j=0;j<values.length-1-i;j++){ if(values[j]>values[j+1]){ temp=values[j]; values[j]=values[j+1]; values[j+1]=temp; flag=false; } System.out.println(Arrays.toString(values)); } if(flag){ System.out.println("结束!!!"); break; } } } } 运行结果 ######第1趟 比较9次 [1, 3, 6, 2, 9, 0, 7, 4, 5, 8] [1, 3, 6, 2, 9, 0, 7, 4, 5, 8] [1, 3, 2, 6, 9, 0, 7, 4, 5, 8] [1, 3, 2, 6, 9, 0, 7, 4, 5, 8] [1, 3, 2, 6, 0, 9, 7, 4, 5, 8] [1, 3, 2, 6, 0, 7, 9, 4, 5, 8] [1, 3, 2, 6, 0, 7, 4, 9, 5, 8] [1, 3, 2, 6, 0, 7, 4, 5, 9, 8] [1, 3, 2, 6, 0, 7, 4, 5, 8, 9] ######第2趟 比较8次 [1, 3, 2, 6, 0, 7, 4, 5, 8, 9] [1, 2, 3, 6, 0, 7, 4, 5, 8, 9] [1, 2, 3, 6, 0, 7, 4, 5, 8, 9] [1, 2, 3, 0, 6, 7, 4, 5, 8, 9] [1, 2, 3, 0, 6, 7, 4, 5, 8, 9] [1, 2, 3, 0, 6, 4, 7, 5, 8, 9] [1, 2, 3, 0, 6, 4, 5, 7, 8, 9] [1, 2, 3, 0, 6, 4, 5, 7, 8, 9] ######第3趟 比较7次 [1, 2, 3, 0, 6, 4, 5, 7, 8, 9] [1, 2, 3, 0, 6, 4, 5, 7, 8, 9] [1, 2, 0, 3, 6, 4, 5, 7, 8, 9] [1, 2, 0, 3, 6, 4, 5, 7, 8, 9] [1, 2, 0, 3, 4, 6, 5, 7, 8, 9] [1, 2, 0, 3, 4, 5, 6, 7, 8, 9] [1, 2, 0, 3, 4, 5, 6, 7, 8, 9] ######第4趟 比较6次 [1, 2, 0, 3, 4, 5, 6, 7, 8, 9] [1, 0, 2, 3, 4, 5, 6, 7, 8, 9] [1, 0, 2, 3, 4, 5, 6, 7, 8, 9] [1, 0, 2, 3, 4, 5, 6, 7, 8, 9] [1, 0, 2, 3, 4, 5, 6, 7, 8, 9] [1, 0, 2, 3, 4, 5, 6, 7, 8, 9] ######第5趟 比较5次 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ######第6趟 比较4次 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 结束!!!
这篇关于Java--冒泡排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南