Update bubble_sort.md
add c version of the code 增加c语言版本的代码
This commit is contained in:
parent
6a380b4157
commit
759e5caf4c
@ -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#"
|
||||
|
Loading…
Reference in New Issue
Block a user