mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-05 12:14:20 +00:00
Add the TypeScript code to docs (Chapter of Sorting)
This commit is contained in:
@@ -150,7 +150,21 @@ comments: true
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="bubble_sort.ts"
|
||||
|
||||
/* 冒泡排序 */
|
||||
function bubbleSort(nums: number[]): void {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// 内循环:冒泡操作
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
@@ -297,7 +311,24 @@ comments: true
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="bubble_sort.ts"
|
||||
|
||||
/* 冒泡排序(标志优化)*/
|
||||
function bubbleSortWithFlag(nums: number[]): void {
|
||||
// 外循环:待排序元素数量为 n-1, n-2, ..., 1
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
let flag = false; // 初始化标志位
|
||||
// 内循环:冒泡操作
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// 交换 nums[j] 与 nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true; // 记录交换元素
|
||||
}
|
||||
}
|
||||
if (!flag) break; // 此轮冒泡未交换任何元素,直接跳出
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
Reference in New Issue
Block a user