Update bubble_sort.md

C++使用std::swap()交换数组,同时添加C语言代码,作为原始C++代码的补充
This commit is contained in:
L-Super 2022-12-26 10:17:35 +08:00 committed by GitHub
parent 18c43566b4
commit 770e3ca4ce
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -85,9 +85,7 @@ comments: true
for (int j = 0; j < i; j++) { for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) { if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1] // 交换 nums[j] 与 nums[j + 1]
int tmp = nums[j]; std::swap(nums[j], nums[j+1]);
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
} }
} }
} }
@ -170,7 +168,24 @@ comments: true
=== "C" === "C"
```c title="bubble_sort.c" ```c title="bubble_sort.c"
/* 冒泡排序 */
void bubble_sort(int nums[], int size)
{
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (int i = 0; i < size - 1; i++)
{
// 内循环:冒泡操作
for (int j = 0; j < size - 1 - i; j++)
{
if (nums[j] > nums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}
``` ```
=== "C#" === "C#"
@ -250,9 +265,7 @@ comments: true
for (int j = 0; j < i; j++) { for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) { if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1] // 交换 nums[j] 与 nums[j + 1]
int tmp = nums[j]; std::swap(nums[j], nums[j+1]);
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 记录交换元素 flag = true; // 记录交换元素
} }
} }
@ -352,7 +365,27 @@ comments: true
=== "C" === "C"
```c title="bubble_sort.c" ```c title="bubble_sort.c"
/* 冒泡排序 */
void bubble_sort(int nums[], int size)
{
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
for (int i = 0; i < size - 1; i++)
{
bool flag = false;
// 内循环:冒泡操作
for (int j = 0; j < size - 1 - i; j++)
{
if (nums[j] > nums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
flag = true;
}
}
if(!falg) break;
}
}
``` ```
=== "C#" === "C#"