冒泡排序

This commit is contained in:
flykhan 2023-07-25 20:25:58 +08:00
parent b19828f9e4
commit 5f5d157621
2 changed files with 80 additions and 0 deletions

41
chapter1/bubble_sort.c Normal file
View File

@ -0,0 +1,41 @@
#include <stdio.h>
int main()
{
int a[100], i, j, t, n;
scanf("%d", &n); // 输入一个数,表示接下来有 n 个数
for (i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
// 冒泡排序的核心部分
for (i = 1; i <= n - 1; i++) // n 个数排序,只用进行 n - 1 趟
{
// 从第 1 位开始比较直到最后一个尚未归位的数,想一想为什么到 n - i 就可以了
for (j = 1; j <= n - i; j++)
{
if (a[j] < a[j + 1]) // 比较大小并交换
{
// t = a[j];
// a[j] = a[j + 1];
// a[j + 1] = t;
// 位运算交换
a[j] ^= a[j + 1];
a[j + 1] ^= a[j];
a[j] ^= a[j + 1];
}
}
}
for (i = 1; i <= n; i++) // 输出结果
printf("%d ", a[i]);
getchar();
getchar();
return 0;
return 0;
}

39
chapter1/d3.c Normal file
View File

@ -0,0 +1,39 @@
#include <stdio.h>
struct student
{
char name[21]; // 21 个字节
int score;
};
int main()
{
struct student a[100], t;
int i, j, n;
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
scanf("%s %d", a[i].name, &a[i].score);
}
for (i = 1; i <= n - 1; i++)
{
for (j = 1; j <= n - i; j++)
{
if (a[j].score < a[j + 1].score)
{
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
printf("\033[2J");
for (int i = 1; i <= n; i++)
printf("%s\n", a[i].name);
getchar();
getchar();
return 0;
}