📄 bubblesort.cpp
字号:
/************************************
* Copyright (c) 2008,LDCI
*
* 文件名称: BobbleSort.cpp
* 摘要:
* 使用 C 语言实现对顺序存储结构的线性表进行冒泡排序
************************************/
#include <stdlib.h>
#include <stdio.h>
#define LISTSIZE 100 // 表的长度,根据实际情况而定
typedef int DataType; // 数据,根据实际情况而定
typedef struct
{
DataType data[LISTSIZE]; // 存放所有数据的空间
int nLength; // 当前表的长度
}SeqList;
void Show(SeqList* _pList)
{
for(int i=0; i<_pList->nLength; i++)
{
printf("%d, ", _pList->data[i]);
}
printf("\n");
}
/**************************************************
* 函数名: BobbleSort
* 参数:
* 形参:
* _pList : 顺序存储结构的线性表
* 返回值: 无
* 功能:
* 对顺序存储结构的线性表进行冒泡排序
* 作者: 左建华
* 编写明细:
* 2008-06-01 Created 左建华
*
**************************************************/
void BobbleSort( SeqList* _pList )
{
bool bExchangeFlag;
for(int i=1;i<_pList->nLength;i++) // 最多做 length-1 趟排序
{
bExchangeFlag = false; // 本趟排序开始前,将交换标志为假
for(int j=0;j<_pList->nLength-i;j++) // 开始扫描区间
{
if(_pList->data[j]>_pList->data[j+1]) // 交换元素
{
int nTemp=_pList->data[j];
_pList->data[j]=_pList->data[j+1];
_pList->data[j+1]=nTemp;
bExchangeFlag = true; // 只要发生了交换,即将交换标志为真
}
}
if(!bExchangeFlag) // 本趟排序未发生交换,则提前终止算法
{
return ;
}
// Show(_pList);
} // endfor
}
int main(int argc, char** argv)
{
SeqList* pList = (SeqList*)malloc(sizeof(SeqList));
pList->nLength = 8;
pList->data[0] = 49;
pList->data[1] = 38;
pList->data[2] = 65;
pList->data[3] = 97;
pList->data[4] = 76;
pList->data[5] = 13;
pList->data[6] = 27;
pList->data[7] = 49;
Show(pList);
BobbleSort(pList);
Show(pList);
free(pList);
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -