16.4 冒泡排序

题目简介

排序动画模拟网站

phttps://www.cs.usfca.edugalles/visualization/ComparisonSort.htm

简洁版

cpp 复制代码
#include <stdio.h>
int main()
{
	int a[10]={9,3,6,5,8,2,4,1,7,0};
	int n = sizeof(a)/sizeof(int);
	int temp = 0;
	for(int j=0;j<n-1;j++){	//外层循环循环9轮即可
		for(int i=n-1;i>j;i--){
			if(a[i]<a[i-1]){
				temp=a[i];
				a[i]=a[i-1];
				a[i-1]=temp;
			}
		}
	}
	for(int i=0;i<n;i++){
		printf("%2d",a[i]);
	}
	return 0;
}
bash 复制代码
0 1 2 3 4 5 6 7 8 9

正式版

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef int ElemType;
typedef struct{
	ElemType *elem;//存储元素起始地址
	int TableLen;//元素个数
}SSTable;

void ST_Init(SSTable &ST,int len)
{
	ST.TableLen = len;
	ST.elem = (ElemType *)malloc(sizeof(ElemType)*ST.TableLen);//申请一块堆空间,当数组用
	srand(time(NULL));//随机数生成,这句代码记住即可
	for(int i = 0; i < ST.TableLen; i++) {
		ST.elem[i] = rand() % 100;//生成的是0-99之间
	}
}

void ST_print(SSTable ST)//打印数组
{
	for(int i = 0; i < ST.TableLen; i++) {
		printf("%3d", ST.elem[i]);
	}
	printf("\n");
}

void swap(ElemType &a, ElemType &b)
{
	ElemType temp;
	temp = a;
	a = b;
	b = temp;
}

void BubbleSort(ElemType A[], int n)
{
	bool flag;
	for(int i = 0; i < n-1; i++) { //循环n-1轮,访问到n-2
		flag = false; //元素是否发生交换的标志
		for(int j = n-1; j > i; j--) {
			if(A[j] < A[j-1]) {
				swap(A[j], A[j-1]);
				flag = true;
			}
		}
		if(false == flag) //如果一趟比较没有发生任何交换,说明有序,提前结束排序
			return;
	}
}

int main()
{
	SSTable ST;
	ST_Init(ST, 10); //初始化
	ST_print(ST); //排序前打印
	
	BubbleSort(ST.elem, 10);
	ST_print(ST); //排序后打印
	
	return 0;	
}
bash 复制代码
97 25 44 66 29  2 98 61 13 76
 2 13 25 29 44 61 66 76 97 98
相关推荐
羊小蜜.4 分钟前
Mysql 03: 连接查询全解——内连接、外连接与复合条件查询
数据库·mysql·算法·连接查询
vivo互联网技术12 分钟前
CVPR 2026 | C²FG:用分数差异分析提高条件生成中CFG的引导
人工智能·算法·aigc
Mr_Xuhhh1 小时前
算法题解博客:三道经典题目的思路与实现
算法
算法-大模型备案 多米1 小时前
大模型备案实操指南:材料、流程与避坑要点
大数据·网络·人工智能·算法·文心一言
顾温1 小时前
数据转换函数
开发语言·算法
汉克老师1 小时前
GESP2025年6月认证C++三级( 第三部分编程题(1、奇偶校验)
c++·算法·gesp三级·gesp3级·按位操作
Fcy6481 小时前
算法基础详解(一)模拟算法与高精度算法
算法·模拟算法·高精度算法
Promise微笑1 小时前
算法对齐还是实战突围?解构GEO优化中方法论与实践的权重博弈
算法
米粒12 小时前
力扣算法刷题 Day 29
算法·leetcode·职场和发展
wfbcg2 小时前
每日算法练习:LeetCode 125. 验证回文串 ✅
算法·leetcode·职场和发展