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
相关推荐
??tobenewyorker14 分钟前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
蓝澈112122 分钟前
迪杰斯特拉算法之解决单源最短路径问题
java·数据结构
贾全36 分钟前
第十章:HIL-SERL 真实机器人训练实战
人工智能·深度学习·算法·机器学习·机器人
GIS小天1 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年7月4日第128弹
人工智能·算法·机器学习·彩票
满分观察网友z1 小时前
开发者的“右”眼:一个树问题如何拯救我的UI设计(199. 二叉树的右视图)
算法
森焱森2 小时前
无人机三轴稳定化控制(1)____飞机的稳定控制逻辑
c语言·单片机·算法·无人机
循环过三天2 小时前
3-1 PID算法改进(积分部分)
笔记·stm32·单片机·学习·算法·pid
呆瑜nuage3 小时前
数据结构——堆
数据结构
蓝澈11213 小时前
弗洛伊德(Floyd)算法-各个顶点之间的最短路径问题
java·数据结构·动态规划
zl_dfq3 小时前
数据结构 之 【堆】(堆的概念及结构、大根堆的实现、向上调整法、向下调整法)(C语言实现)
数据结构