網站首頁 編程語言 正文
冒泡排序(Bubble Sort)也是一種簡單直觀的排序算法。它重復遍歷要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。遍歷數列的工作是重復地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個算法的名字由來是因為越小的元素會經由交換慢慢"浮"到數列的頂端。
1.算法步驟
比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最后一對。這步做完后,最后的元素會是最大的數。
針對所有的元素重復以上的步驟,除了最后一個。
持續每次對越來越少的元素重復上面的步驟,直到沒有任何一對數字需要比較。
2.動圖演示
3.C語言
#include <stdio.h>
void bubble_sort(int arr[], int len)
{
int i, j, temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
int main()
{
int arr[] = {22, 34, 34, 9, 81, 55, 20, 50, 37, 5, 64, 8, 12, 70};
int len = (int)sizeof(arr) / sizeof(*arr);
bubble_sort(arr, len);
int i;
for (i = 0; i < len; i++)
printf("%d ", arr[i]);
return 0;
}
4.C++語言
#include <iostream>
using namespace std;
template <typename T> //整數或浮點數皆可使用,若要使用類(class)或結構體(struct)時必須重載大于(>)運算符
void bubble_sort(T arr[], int len)
{
int i, j;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1])
swap(arr[j], arr[j + 1]);
}
int main()
{
int arr[] = {56, 19, 26, 21, 22, 60, 56, 21, 90, 14, 62};
int len = (int)sizeof(arr) / sizeof(*arr);
bubble_sort(arr, len);
for (int i = 0; i < len; i++)
cout << arr[i] << ' ';
cout << endl;
float arrf[] = {17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4};
len = (float)sizeof(arrf) / sizeof(*arrf);
bubble_sort(arrf, len);
for (int i = 0; i < len; i++)
cout << arrf[i] << ' ' << endl;
return 0;
}
原文鏈接:https://blog.csdn.net/qq_44394562/article/details/125910028
相關推薦
- 2022-11-05 Kotlin?Select協程多路復用的實現詳解_Android
- 2023-07-07 更新node后項目報錯
- 2022-04-15 golang數組和切片作為參數和返回值的實現_Golang
- 2022-05-22 Flutter應用框架搭建之屏幕適配詳解_Android
- 2022-04-23 如何在vs-code 中進行debugger調試
- 2022-12-28 kotlin開發cli工具小技巧詳解_Android
- 2022-04-09 iOS浮點類型精度問題的原因與解決辦法_IOS
- 2022-07-19 react組件通訊的三種方式props:父組件和子組件互相通訊、兄弟組件通訊
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支