关闭

冒泡排序

标签: algorithmnumberseach
405人阅读 评论(0) 收藏 举报
分类:

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

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 + "  ");
		}
	}


 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:97699次
    • 积分:1401
    • 等级:
    • 排名:千里之外
    • 原创:57篇
    • 转载:1篇
    • 译文:0篇
    • 评论:14条
    文章分类
    最新评论