mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-05 11:41:22 +08:00
Update the comments of bubble sort
and insertion sort
This commit is contained in:
@@ -8,9 +8,9 @@
|
||||
|
||||
/* 冒泡排序 */
|
||||
void bubbleSort(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
// 外循环:未排序区间为 [0, i]
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
// 内循环:冒泡操作
|
||||
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
for (int j = 0; j < size - 1 - i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
int temp = nums[j];
|
||||
@@ -23,10 +23,10 @@ void bubbleSort(int nums[], int size) {
|
||||
|
||||
/* 冒泡排序(标志优化)*/
|
||||
void bubbleSortWithFlag(int nums[], int size) {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
// 外循环:未排序区间为 [0, i]
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
bool flag = false;
|
||||
// 内循环:冒泡操作
|
||||
// 内循环:将未排序区间 [0, i] 中的最大元素交换至该区间的最右端
|
||||
for (int j = 0; j < size - 1 - i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
int temp = nums[j];
|
||||
|
||||
@@ -8,16 +8,16 @@
|
||||
|
||||
/* 插入排序 */
|
||||
void insertionSort(int nums[], int size) {
|
||||
// 外循环:base = nums[1], nums[2], ..., nums[n-1]
|
||||
// 外循环:已排序元素数量为 1, 2, ..., n
|
||||
for (int i = 1; i < size; i++) {
|
||||
int base = nums[i], j = i - 1;
|
||||
// 内循环:将 base 插入到左边的正确位置
|
||||
// 内循环:将 base 插入到已排序部分的正确位置
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
// 1. 将 nums[j] 向右移动一位
|
||||
// 将 nums[j] 向右移动一位
|
||||
nums[j + 1] = nums[j];
|
||||
j--;
|
||||
}
|
||||
// 2. 将 base 赋值到正确位置
|
||||
// 将 base 赋值到正确位置
|
||||
nums[j + 1] = base;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user