Bubble Sort

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 )

.....

复制代码
 1 class Solution {
 2   public static int[] bubbleSort(int[] num) { 
 3     for (c = num.length - 1; c >= 0; c--) {
 4       for (d = 0; d < c; d++) {
 5         if (array[d] > array[d+1])
 6         {
 7           //swap
 8           int swap       = array[d];
 9           array[d]   = array[d+1];
10           array[d+1] = swap;
11         }
12       }
13       return num;
14     }
15 }
复制代码

Time complexity O(n^2), space cost O(1), and it's in-place sorting.

posted @   树獭君  阅读(126)  评论(0编辑  收藏  举报
编辑推荐:
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
阅读排行:
· Apifox不支持离线,Apipost可以!
· 历时 8 年,我冲上开源榜前 8 了!
· 零经验选手,Compose 一天开发一款小游戏!
· Trae 开发工具与使用技巧
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示