冒泡排序

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

思路:确定趟数,需要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;
}

程序结果:

相关推荐
IronMurphy14 小时前
【算法二十二】 739. 每日温度 42.接雨水
算法
一轮弯弯的明月14 小时前
竞赛刷题-建造最大岛屿-Java版
java·算法·深度优先·图搜索算法·学习心得
黑眼圈子14 小时前
牛客刷题记录1
算法
祁同伟.14 小时前
【C++】哈希的应用
开发语言·数据结构·c++·算法·容器·stl·哈希算法
点云SLAM14 小时前
Tracy Profiler 是目前 C++ 多线程程序实时性能分析工具
开发语言·c++·算法·slam·算法性能分析·win环境性能分析·实时性能分析工具
每天回答3个问题14 小时前
leetcodeHot100|148.排序链表
数据结构·c++·链表·ue4
We་ct14 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·leetcode·typescript·深度优先·深度优先遍历
吃着火锅x唱着歌14 小时前
LeetCode 447.回旋镖的数量
算法·leetcode·职场和发展
我能坚持多久14 小时前
【初阶数据结构08】——深入理解树与堆
数据结构·算法
Trouvaille ~14 小时前
【贪心算法】专题(一):从局部到全局,数学证明下的最优决策
c++·算法·leetcode·面试·贪心算法·蓝桥杯·竞赛