Bubble Sort
2015-10-06 05:27
295 查看
referrence: GeeksforGeeks
Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
After first pass, we put largest bubble at bottom.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 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.
After second pass, we put second largest bubble at bottom.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
.....
Time complexity O(n^2), space cost O(1), and it's in-place sorting.
Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.
After first pass, we put largest bubble at bottom.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 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.
After second pass, we put second largest bubble at bottom.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
.....
class Solution { public static int[] bubbleSort(int[] num) { for (c = num.length - 1; c >= 0; c--) { for (d = 0; d < c; d++) { if (array[d] > array[d+1]) { //swap int swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } return num; } }
Time complexity O(n^2), space cost O(1), and it's in-place sorting.
相关文章推荐
- Seletion Sort
- 如何解决HTC Desire 826无法使用谷歌服务的问题
- 浅谈vector存储内容与空间利用
- App 推荐:Spotify
- Binary Search
- 去掉UITableView的Cell选中状态
- 如何策划一个符合seo标准的网站(详细思路)
- Linux 内核 0.01 发布纪念日:协作的价值
- 超越竞争对手上首页SEO优化方案
- android 界面控件被输入法顶起来解决
- 纯PHP实现定时器任务(Timer)
- 导航菜单栏制作
- MySQL常用查询语句
- Linux常见应用--DNS服务器常见应用实现
- PHP setcookie()用法
- Privileged containers provisioning by Kubernetes in Ubuntu
- PDO
- Windows 64位下安装Redis详细教程
- Leetcode Meeting Rooms
- DooDigestAuth php(后台)授权管理类 web浏览器授权