冒泡排序

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

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

程序结果:

相关推荐
生态学者9 小时前
Global Change Biology | 森林越“步调一致”,反而越怕干旱?树木生长与叶片活动的同步之谜
大数据·人工智能·算法·r语言·微信公众平台
lsswear9 小时前
Agent 框架新手入门与实战部署指南
大数据·人工智能·算法
学逆向的9 小时前
C 循环结构的执行效率分析
c语言·开发语言·数据结构·网络安全
Data analyse45611 小时前
rnweb 回放数据量太大怎么办?分片存储与断点续传的实现思路
前端·网络·算法·数据分析
Navigator_Z12 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil20813 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
光影少年13 小时前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.33313 小时前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
jeo陽13 小时前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构
Nil20813 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展