首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >数据结构上机——双向起泡排序

数据结构上机——双向起泡排序

作者头像
zstar
发布2022-06-14 09:28:14
发布2022-06-14 09:28:14
4660
举报
文章被收录于专栏:往期博文往期博文

相比于传统的冒泡排序 双向气泡排序做了两点优化: 1、利用flag标记有无数据交换,防止在数据有序的情况下再次浪费时间 2、每次循环,从前往后又从后往前,每次确定一个大的一个小的,大小通吃

代码语言:javascript
复制
//双向起泡排序的程序代码
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//顺序表结构类型定义
typedef int datatype;
typedef struct{
	int key;
	datatype data;
}sequenlist;

void create(sequenlist[],int);
void print(sequenlist[],int);
void dbubblesort(sequenlist[],int);

int main()
{
	const int n=10;
	sequenlist r[n+1];
	create(r,n);
	printf("排序前的数据:");
	print(r,n);
	dbubblesort(r,n);
	printf("排序后的数据:");
	print(r,n);
}

//建立顺序表
void create(sequenlist r[],int n)
{
	srand(time(0));
	for(int i=1;i<=n;i++)
		r[i].key=rand()%90;
}

//输出顺序表
void print(sequenlist r[],int n)
{
	for(int i=1;i<=n;i++)
		printf("%5d",r[i].key);
	printf("\n");
}

//添加双向起泡排序算法
void dbubblesort(sequenlist r[],int n)
{
	int low=1,high=n,flag,i,temp;
	while (low<high)
	{
		flag=0;//flag标记有无数据交换 
		for(i=low;i<high;i++)
		{
			if(r[i].key>r[i+1].key)
			{
				temp=r[i].key;
				r[i].key=r[i+1].key;
				r[i+1].key=temp;
				flag=1;
			}	
		}
		if(flag==0)break;
		high--;
		for(i=high;i>low;i--)
		{
			if(r[i].key<r[i-1].key)
			{
				temp=r[i].key;
				r[i].key=r[i-1].key;
				r[i-1].key=temp;
			} 
		}
		low++; 
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-12-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档