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
相关推荐
leoufung3 分钟前
LeetCode 322. Coin Change:从错误思路到正确一维 DP
算法·leetcode·职场和发展
旧梦吟6 分钟前
脚本网页 双子星棋
算法·flask·游戏引擎·css3·html5
ullio12 分钟前
arc205d - Non-Ancestor Matching
算法
wa的一声哭了19 分钟前
内积空间 正交与正交系
java·c++·线性代数·算法·矩阵·eclipse·云计算
SWAGGY..23 分钟前
数据结构学习篇(8)---二叉树
数据结构·学习·算法
星轨初途25 分钟前
牛客小白月赛126
开发语言·c++·经验分享·笔记·算法
leoufung30 分钟前
动态规划DP 自我提问模板
算法·动态规划
爱编程的小吴37 分钟前
【力扣练习题】热题100道【哈希】560. 和为 K 的子数组
算法·leetcode·哈希算法
じ☆冷颜〃37 分钟前
基于多数据结构融合的密码学性能增强框架
数据结构·经验分享·笔记·python·密码学
Swift社区42 分钟前
LeetCode 463 - 岛屿的周长
算法·leetcode·职场和发展