冒泡排序

原创 2012年03月26日 15:17:39

思路为相邻两个依次比较,

Step-by-step example

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number to greatest number using bubble sort algorithm. In each step, elements written in bold are being compared. Three passes will be required.

First Pass:
( 5 1 4 2 8 ) \to ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps them.
( 1 5 4 2 8 ) \to ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) \to ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
Second Pass:
( 1 4 2 5 8 ) \to ( 1 4 2 5 8 )
( 1 4 2 5 8 ) \to ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )
( 1 2 4 5 8 ) \to ( 1 2 4 5 8 )

代码实现如下:

public static void bubbleSort(int [] a){
		for(int i = 0;i<a.length - 1;i++){
			boolean swap = false;
			for(int j = 1;j<a.length -i ;j++){
				if(a[j-1] > a[j]){
					int temp = a[j - 1];
					a[j - 1] = a[j];
					a[j] = temp;
					swap = true;
				}		
			}
			if(swap == false){
				System.out.println("break");
				break;
			}
		}
		
		for(int i:a){
			System.out.print(i + "  ");
		}
	}


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

奇偶冒泡排序

冒泡排序C语言

  • 2016-02-18 18:57
  • 652B
  • 下载

经典白话算法之冒泡排序

简化版的桶排序不仅仅有上一节所遗留的问题,更要命的是:它非常浪费空间!例如需要排序数的范围是0~2100000000之间,那你则需要申请2100000001个变量,也就是说要写成int a[21000...

数据结构之冒泡排序

  • 2017-08-23 10:35
  • 178KB
  • 下载

冒泡排序及其优化

/** * 冒泡排序及其优化 * @author shuaicenglou * */ public class Maopao { public static void main(Str...

JAVA冒泡排序及其优化

arm汇编冒泡排序

  • 2016-01-14 15:21
  • 812B
  • 下载

java冒泡排序

public class BubbleSort { public static void main(String[] args) { // 创建一个数组,这个数组元素是乱序的 int[] a...

冒泡排序VB版

  • 2015-03-28 21:43
  • 27KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)