This commit is contained in:
krahets
2023-10-08 01:43:28 +08:00
parent 3d2d669b43
commit baac2d11a7
52 changed files with 999 additions and 625 deletions
+4 -8
View File
@@ -102,16 +102,14 @@ comments: true
```csharp title="bubble_sort.cs"
/* 冒泡排序 */
void bubbleSort(int[] nums) {
void BubbleSort(int[] nums) {
// 外循环:未排序区间为 [0, i]
for (int i = nums.Length - 1; i > 0; 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;
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
}
}
}
@@ -353,7 +351,7 @@ comments: true
```csharp title="bubble_sort.cs"
/* 冒泡排序(标志优化)*/
void bubbleSortWithFlag(int[] nums) {
void BubbleSortWithFlag(int[] nums) {
// 外循环:未排序区间为 [0, i]
for (int i = nums.Length - 1; i > 0; i--) {
bool flag = false; // 初始化标志位
@@ -361,9 +359,7 @@ comments: true
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;
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
flag = true; // 记录交换元素
}
}