Add cpp codes for the chapter
computational complexity, sorting, searching.
This commit is contained in:
@@ -56,7 +56,7 @@ comments: true
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java
|
||||
```java title="bubble_sort.java"
|
||||
/* 冒泡排序 */
|
||||
void bubbleSort(int[] nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
@@ -73,10 +73,29 @@ comments: true
|
||||
}
|
||||
}
|
||||
```
|
||||
=== "C++"
|
||||
|
||||
```cpp title="bubble_sort.cpp"
|
||||
/* 冒泡排序 */
|
||||
void bubbleSort(vector<int>& nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = nums.size() - 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
```python title="bubble_sort.py"
|
||||
""" 冒泡排序 """
|
||||
def bubble_sort(nums):
|
||||
n = len(nums)
|
||||
@@ -109,7 +128,7 @@ comments: true
|
||||
|
||||
=== "Java"
|
||||
|
||||
```java
|
||||
```java title="bubble_sort.java"
|
||||
/* 冒泡排序(标志优化)*/
|
||||
void bubbleSortWithFlag(int[] nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
@@ -130,9 +149,32 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "C++"
|
||||
|
||||
```cpp title="bubble_sort.cpp"
|
||||
/* 冒泡排序(标志优化)*/
|
||||
void bubbleSortWithFlag(vector<int>& nums) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (int i = nums.size() - 1; i > 0; i--) {
|
||||
bool flag = false; // 初始化标志位
|
||||
// 内循环:冒泡操作
|
||||
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 = true; // 记录交换元素
|
||||
}
|
||||
}
|
||||
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
```python title="bubble_sort.py"
|
||||
""" 冒泡排序(标志优化) """
|
||||
def bubble_sort_with_flag(nums):
|
||||
n = len(nums)
|
||||
|
Reference in New Issue
Block a user