冒泡排序

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

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

程序结果:

相关推荐
伊玛目的门徒2 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry2 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵4 小时前
【无标题】
数据结构·算法
Kx_Triumphs5 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎5 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀7 小时前
约瑟夫环问题
算法
凤凰院凶涛QAQ8 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
科技大视界8 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴9 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法