数据结构-排序-冒泡排序
1.算法思想
- 冒泡排序的思想: 对所有记录以从左到右的排列,对两相邻的排序码比较,如果大于(或者小于)就交换这两个记录。这样每一趟的比较,最大(或者最小的)的记录就会放到 ''最后一个位置"(是每次比较的范围的最后一个位置,并不是实际记录的最后,因为每次排完最后一个最大的元素,下一次不在比较的范围内,即范围会减一),
- 动图便于理解,图片来自于菜鸟教程
2.算法复杂度
- 执行时间: O(n^2)
- 附加空间: 一个交换时使用的附加空间
- 是否是稳定的排序方法: 稳定
3.算法实现
#include "stdio.h"
#define MAXSIZE 10
typedef int keytype;
typedef struct {
keytype key;
int other;
}recordtype;
typedef struct {
int length;
recordtype r[MAXSIZE + 1];
}table;
void bubblesort(table * tab) {
int i, j;
//外围是每一趟的循环,每次循环都会把最大排序码的记录排到这次比较的最后面,然后下一趟 比较的记录数减一
for (i = 1; i < tab->length; i++)
{
//内部比较交换循环
for (j = 1; j < tab->length - i; j++)
{
//如果前面的记录排序码大于后面的记录的排序码则交换
if (tab->r[j].key>tab->r[j + 1].key) {
tab->r[0] = tab->r[j + 1];
tab->r[j + 1] = tab->r[j];
tab->r[j] = tab->r[0];
}
}
}
}
void inputData(table * tab) {
printf("please input the length:\n");
scanf("%d", &tab->length);
printf("please input the data:");
for (int i = 1; i <= tab->length; i++)
{
scanf("%d", &tab->r[i].key);
}
return tab;
}
void show(table * tab) {
printf("the result data:");
for (int i = 1; i <= tab->length; i++)
{
printf("%d ", tab->r[i].key);
}
}
void main() {
table * tab = malloc(sizeof(table));
inputData(tab);
bubblesort(tab);
show(tab);
}
运行截图
欢迎大家关注我的博客:breeziness123
转载说明出处