1. 什么是冒泡排序?(摘抄自百度百科)
冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法。
它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳的气泡最终会上浮到顶端一样,故名“冒泡排序”。
2. 冒泡排序算法原理(摘抄自百度百科)
① 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
② 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。
③ 针对所有的元素重复以上的步骤,除了最后一个。
④ 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
3.冒泡排序算法实现
# include <stdio.h>
# include <stdlib.h>
# include <malloc.h>
# include <conio.h>
# include <string.h>
# include <math.h>
# define LISTINITSIZE 20
# define LISTINCREAMENT 5
# define OK 1
# define ERROR 0
typedef int ElemType;
//定义顺序表结构
typedef struct
{
ElemType *elem;
int length;
int listsize;
}SeqList;
//初始化
int InitList(SeqList *L)
{
L->elem=(ElemType *)malloc(sizeof(ElemType)*LISTINITSIZE);
if(!(L->elem))
return ERROR;
L->length=0;
L->listsize=LISTINITSIZE;
return OK;
}
//打印
void PrintList(SeqList *L)
{
int i;
for(i=1;i<=L->length;i++)
{
printf("%d ",L->elem[i]);
}
printf("\n");
}
//创建顺序表 (插入元素)
int InsertList(SeqList *L,int i, ElemType e)
{
int j,newspacesize;
ElemType *newbase;
if(i<1||i>L->length+1)
return ERROR;
if(L->length>=L->listsize)
{
newspacesize=(L->listsize+LISTINCREAMENT)*sizeof(ElemType);
newbase=(ElemType *)realloc(L->elem,newspacesize);
if(!(newbase))
return ERROR;
L->elem=newbase;
L->listsize+=LISTINCREAMENT;
}
for(j=L->length;j>=i;j--)
L->elem[j+1]=L->elem[j];
L->elem[i]=e;
L->length++;
return OK;
}
//冒泡算法(从大到小)
void BubbleSort(SeqList *L)
{
int i,j;
int f=0;
for(i=L->length;i>=2&&f==0;i--){
f=1;
for(j=1;j<=i-1;j++)
if(L->elem[j]<L->elem[j+1]){
L->elem[0]=L->elem[j];
L->elem[j]=L->elem[j+1];
L->elem[j+1]=L->elem[0];
f=0;
}
PrintList(L);
}
}
//主函数
int main()
{
SeqList L;
// ElemType a[9]={0,49,38,65,97,76,13,27,49};
int i,N,num;
InitList(&L);
scanf("%d",&N);
for(i=1;i<=N;i++)
{
scanf("%d",&num);
InsertList(&L,i,num);
}
BubbleSort(&L);
return 0;
}
从小到大:
//冒泡算法
void BubbleSort(SeqList *L)
{
int i,j;
int f=0;
for(i=L->length;i>=2&&f==0;i--){
f=1;
for(j=1;j<=i-1;j++)
if(L->elem[j]>L->elem[j+1]){
L->elem[0]=L->elem[j];
L->elem[j]=L->elem[j+1];
L->elem[j+1]=L->elem[0];
f=0;
}
PrintList(L);
}
今天的内容就是这样,欢迎各位小伙伴们,提出问题,私信我哦!