【基础算法】简单排序-冒泡排序
【基础算法】简单排序-冒泡排序
Bubble Sort is the simplest sorting algorithm that works by repeatly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
How does Bubble Sort Work?
Input: arr[]={5,1,4,2,8}
First Pass:
- Bubble sort starts with very first two elements, comparing them to check which one is greater.
- ( 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.
Second Pass:
- Now, during second iteration it should look like this:
- ( 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 )
Third Pass:
- 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.
- ( 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 )
Code:
#include <stdio.h>
#include <malloc.h>
int main() {
setbuf(stdout, 0);
int n = 0;
printf("请输入数组长度:");
scanf("%d", &n);
int* nums = malloc(sizeof(int) * n);
for(int i=0; i<n; i++) {
scanf("%d", nums+i);
}
// Sorting
int temp = 0;
for(int i=0; i<n-1; i++) {
for (int j=0; j<n-1-i; j++) {
if (*(nums+j) > *(nums+j+1)) {
temp = *(nums+j);
*(nums+j) = *(nums+j+1);
*(nums+j+1) = temp;
}
}
}
for(int i=0; i<n; i++) {
printf("%d ", *(nums+i));
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理