冒泡排序

问题:将一个数组中的数据利用冒泡排序法进行升序排序

思路:确定趟数,需要n-1趟,然后对每一趟内部进行两两比较,需要比较n-1-i趟。

cpp 复制代码
#include <stdio.h>

//冒泡排序
int bubble_sort(int arr[], int sz)
{
	int i = 0;
	//确定趟数
	for (i = 0; i < sz - 1; i++)
	{
		int j = 0;
		//每一趟内部两两排序
		for (j = 0; j < sz - 1 - i; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int tmp = 0;
				tmp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = tmp;
			}
		}
	}
}

//打印输出
int print_sort(int arr[], int sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
}
int main()
{
	int arr[] = { 9,3,2,5,6,0,1,4,7,8 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	bubble_sort(arr, sz);
	print_sort(arr, sz);
	return 0;
}

程序结果:

相关推荐
殷色玫瑰5 分钟前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
jidaowansui1 小时前
B3643 图的存储———>数组模拟邻接矩阵
算法
y1su1 小时前
Leetcode 二分模板
java·数据结构·算法·leetcode·排序算法
bksczm1 小时前
数据结构的大纲概括
数据结构
youshi66681 小时前
平衡车——PID算法优化
stm32·单片机·嵌入式硬件·算法·pid·平衡车
千千寰宇2 小时前
[数据库系统] 数据库系统的设计原理研究
数据结构·数据库·database-opengemini/influxdb·database-dament/达梦
聪明蛋子哟2 小时前
不仅仅是向量检索:结合知识图谱与Tool Calling的混合增强生成(Hybrid RAG)方案
人工智能·算法·知识图谱
Pniubi2 小时前
力扣55跳跃游戏(贪心)
算法·leetcode·游戏
jyyyx的算法博客3 小时前
传球游戏【思维】
算法
FL16238631293 小时前
关于2026年南昌大学811信号与系统最后一题电路系统解题思路
算法