網(wǎng)站首頁 編程語言 正文
冒泡排序(Bubble Sort)也是一種簡單直觀的排序算法。它重復(fù)遍歷要排序的數(shù)列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。遍歷數(shù)列的工作是重復(fù)地進行直到?jīng)]有再需要交換,也就是說該數(shù)列已經(jīng)排序完成。這個算法的名字由來是因為越小的元素會經(jīng)由交換慢慢"浮"到數(shù)列的頂端。
1.算法步驟
比較相鄰的元素。如果第一個比第二個大,就交換他們兩個。
對每一對相鄰元素作同樣的工作,從開始第一對到結(jié)尾的最后一對。這步做完后,最后的元素會是最大的數(shù)。
針對所有的元素重復(fù)以上的步驟,除了最后一個。
持續(xù)每次對越來越少的元素重復(fù)上面的步驟,直到?jīng)]有任何一對數(shù)字需要比較。
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> //整數(shù)或浮點數(shù)皆可使用,若要使用類(class)或結(jié)構(gòu)體(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
相關(guān)推薦
- 2022-04-09 react中鍵盤事件無法在div上觸發(fā)的問題解決
- 2024-01-08 Request請求轉(zhuǎn)發(fā)和Response重定向
- 2023-11-11 微信 小程序 在電腦PC端無法加載的解決辦法。電腦微信小程序打不開是怎么回事?電腦微信小程序不能打開
- 2022-07-06 python的import?機制是怎么實現(xiàn)的_python
- 2023-12-13 python處理Excel文檔(一)合并Excel工作表
- 2023-01-02 C語言中g(shù)etchar(?)?函數(shù)使用詳解_C 語言
- 2022-10-01 Redis+Caffeine實現(xiàn)分布式二級緩存組件實戰(zhàn)教程_Redis
- 2022-07-06 C語言舉例講解i++與++i之間的區(qū)別_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支