BubbleSort
来源:互联网 发布:windows player手机版 编辑:程序博客网 时间:2024/05/19 02:00
冒泡算法的核心是相邻的两个元素进行比较,如果左边的数比右边的数要大,则利用一个exch()方法交换两个元素,并且利用一个标识符swap=true,表示数组中的元素仍没有排好序。利用一个for循环进行遍历比较相邻的两个元素。直到数组中是一个有序数组–等价于swap = false。
class BubbleSort { public static void main(String[] args) { int[] a = new int[]{3,44,38,5,47,15,36,26,27,2,46,4,19,50,48}; boolean swap; do { swap=false;//比较完一次后将swap置成false,只要数组中没有交换的元素则执行for循环后就会跳出循环。 for (int i = 0;i<a.length-1 ;i++ ) { if (a[i]>a[i+1]) { exch(a,i,i+1); swap = true; } } } while (swap);//只要swap为true表示数组中的元素进行排序,执行循环体 printArr(a); } public static void exch(int[] a, int i,int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } public static void printArr(int[] a) { for (int i = 0;i<a.length ;i++ ) { if (i==0) { System.out.print("{"+a[i]+","); } else if (i<a.length-1) { System.out.print(a[i]+","); } else System.out.println(a[i]+"}"); } }}
阅读全文
0 0
- BubbleSort
- BubbleSort
- BubbleSort
- bubblesort
- Bubblesort
- BubbleSort
- BubbleSort
- bubblesort
- bubblesort
- bubbleSort
- BubbleSort
- BubbleSort
- BubbleSort
- bubbleSort
- bubbleSort
- BubbleSort
- BubbleSort
- BubbleSort
- 在 Windows 7上安装 TensorFlow
- C#回顾学习笔记二十六:String与StringBuilder的区别
- 红黑树剖析
- 第1章 搭建Android源码工作环境
- finally、final和finalize方法的区别
- BubbleSort
- DPDK+OVS+QEMU搭建vhost-user实验环境
- Hibernate配置以及增删改查实现
- mongoDB启动过程详解
- 大菲波数(递推 + JAVA大数)
- Unity3D计时器四种写法
- iOS代理不回调的多种原因
- hdu 1269
- android活动的启动模式