Update bubble_sort.md

add c version of the code
增加c语言版本的代码
This commit is contained in:
YoHoYes 2022-12-17 21:24:47 +08:00 committed by GitHub
parent 6a380b4157
commit 759e5caf4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -170,7 +170,21 @@ comments: true
=== "C"
```c title="bubble_sort.c"
/* 冒泡排序 */
void bubbleSort(int *nums, int len) {
//外循环: 待排序元素数量为 n-1, n-2, ..., 1
for (int i = len - 1; i > 0; i--) {
//内循环: 冒泡操作
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
```
=== "C#"
@ -334,7 +348,24 @@ comments: true
=== "C"
```c title="bubble_sort.c"
/* 冒泡排序(标志优化)*/
void bubbleSortWithFlag(int *nums, int len) {
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (int i = len - 1; i > 0; i--) {
int flag = 0; // 初始化标志位
// 内循环:冒泡操作
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = 1; // 记录交换元素
}
}
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
}
}
```
=== "C#"