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
相关推荐
legendary_bruce2 小时前
【22-决策树】
算法·决策树·机器学习
艾伦~耶格尔3 小时前
【数据结构进阶】
java·开发语言·数据结构·学习·面试
max5006004 小时前
基于桥梁三维模型的无人机检测路径规划系统设计与实现
前端·javascript·python·算法·无人机·easyui
闪电麦坤955 小时前
数据结构:N个节点的二叉树有多少种(Number of Binary Trees Using N Nodes)
数据结构·二叉树·
快去睡觉~6 小时前
力扣400:第N位数字
数据结构·算法·leetcode
qqxhb7 小时前
零基础数据结构与算法——第七章:算法实践与工程应用-搜索引擎
算法·搜索引擎·tf-idf·倒排索引·pagerank·算法库
gzzeason8 小时前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
汤永红8 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
pusue_the_sun8 小时前
数据结构——顺序表&&单链表oj详解
c语言·数据结构·算法·链表·顺序表
yi.Ist9 小时前
图论——Djikstra最短路
数据结构·学习·算法·图论·好难