From 5f5d1576210c25f7768f308c76b206623d948ce9 Mon Sep 17 00:00:00 2001 From: flykhan Date: Tue, 25 Jul 2023 20:25:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=86=92=E6=B3=A1=E6=8E=92=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- chapter1/bubble_sort.c | 41 +++++++++++++++++++++++++++++++++++++++++ chapter1/d3.c | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 chapter1/bubble_sort.c create mode 100644 chapter1/d3.c diff --git a/chapter1/bubble_sort.c b/chapter1/bubble_sort.c new file mode 100644 index 0000000..44528c1 --- /dev/null +++ b/chapter1/bubble_sort.c @@ -0,0 +1,41 @@ +#include + +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; +} diff --git a/chapter1/d3.c b/chapter1/d3.c new file mode 100644 index 0000000..2a693e6 --- /dev/null +++ b/chapter1/d3.c @@ -0,0 +1,39 @@ +#include + +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; +}