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
相关推荐
皮卡蛋炒饭.7 分钟前
数据结构—排序
数据结构·算法·排序算法
??tobenewyorker1 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
贝塔西塔1 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
众链网络2 小时前
AI进化论08:机器学习的崛起——数据和算法的“二人转”,AI“闷声发大财”
人工智能·算法·机器学习
2 小时前
Unity开发中常用的洗牌算法
java·算法·unity·游戏引擎·游戏开发
飒飒真编程3 小时前
C++类模板继承部分知识及测试代码
开发语言·c++·算法
GeminiGlory3 小时前
算法练习6-大数乘法(高精度乘法)
算法
熬了夜的程序员4 小时前
【华为机试】HJ61 放苹果
算法·华为·面试·golang
马特说4 小时前
基于随机森林的金融时间序列预测系统:从数据处理到实时预测的完整流水线
算法·随机森林·金融
呆呆的小鳄鱼4 小时前
leetcode:HJ18 识别有效的IP地址和掩码并进行分类统计[华为机考][字符串]
算法·leetcode·华为