mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-13 07:46:06 +00:00
build
This commit is contained in:
@@ -134,13 +134,43 @@ comments: true
|
||||
=== "JavaScript"
|
||||
|
||||
```javascript title="selection_sort.js"
|
||||
[class]{}-[func]{selectionSort}
|
||||
/* 选择排序 */
|
||||
function selectionSort(nums) {
|
||||
let n = nums.length;
|
||||
// 外循环:未排序区间为 [i, n-1]
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
// 内循环:找到未排序区间内的最小元素
|
||||
let k = i;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) {
|
||||
k = j; // 记录最小元素的索引
|
||||
}
|
||||
}
|
||||
// 将该最小元素与未排序区间的首个元素交换
|
||||
[nums[i], nums[k]] = [nums[k], nums[i]];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "TypeScript"
|
||||
|
||||
```typescript title="selection_sort.ts"
|
||||
[class]{}-[func]{selectionSort}
|
||||
/* 选择排序 */
|
||||
function selectionSort(nums: number[]): void {
|
||||
let n = nums.length;
|
||||
// 外循环:未排序区间为 [i, n-1]
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
// 内循环:找到未排序区间内的最小元素
|
||||
let k = i;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) {
|
||||
k = j; // 记录最小元素的索引
|
||||
}
|
||||
}
|
||||
// 将该最小元素与未排序区间的首个元素交换
|
||||
[nums[i], nums[k]] = [nums[k], nums[i]];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
=== "C"
|
||||
|
||||
Reference in New Issue
Block a user