Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f5ce945

Browse files
committed
docs: update search algorithm
1 parent 175fffc commit f5ce945

File tree

1 file changed

+38
-30
lines changed

1 file changed

+38
-30
lines changed

‎src/docs/algorithm/search.md

Lines changed: 38 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,63 @@
1-
# 搜索
1+
# 搜索算法
22

3-
找出数组中某个元素的下标
3+
搜索算法简单来说就是用于找出数组中某个元素的下标
44

5-
JavaScript 中的搜索:数组的 `indexOf` 方法。
5+
JavaScript 语言中的自带的搜索:数组的 `indexOf` 方法。
66

77
## 顺序搜索
88

9-
遍历数组,找到目标的元素,就返回它的下标,没有找到返回 -1
9+
顺序搜索(Sequential Search)算法是一种简单的搜索算法,它按顺序检查列表中的每个元素,直到找到目标元素或遍历完整个列表
1010

1111
代码实现:
1212

1313
```js
14-
Array.prototype.sequentialSearch = function (item) {
15-
for (let i = 0; i < this.length; i++) {
16-
if (this[i] === item) {
17-
return i;
14+
function sequentialSearch(array, target) {
15+
// 遍历数组中的每个元素
16+
for (let i = 0; i < array.length; i++) {
17+
// 如果当前元素等于目标元素,则返回当前元素的索引
18+
if (array[i] === target) {
19+
return i
1820
}
1921
}
22+
// 如果未找到目标元素,则返回 -1
2023
return -1
2124
}
25+
26+
// 测试
27+
console.log(sequentialSearch([1, 2, 3, 4, 5], 0)) // -1
28+
console.log(sequentialSearch([1, 2, 3, 4, 5], 3)) // 2
2229
```
2330

24-
顺序搜索的时间复杂度为 O(n)。
31+
顺序搜索的时间复杂度为 O(n),其中 n 是列表的长度
2532

2633
## 二分搜索
2734

28-
从数组的中间元素开始,如果中间元素正好是目标值,则搜索结束。如果目标值大于或者小于中间元素,则在大于或小于中间元素的那一半数组中搜索。
29-
30-
代码实现:
35+
二分搜索(Binary Search)是一种高效的搜索算法,适用于有序数组。该算法通过重复将搜索范围缩小为一半来找到目标值。
3136

3237
```js
33-
Array.prototype.binarySearch = function (item) {
34-
let low = 0;
35-
let high = this.length - 1;
36-
while (low <= high) {
37-
const mid = Math.floor((low + high) / 2);
38-
const element = this[mid];
39-
if (element < item) {
40-
low = mid + 1;
41-
} else if (element > item) {
42-
high = mid - 1;
43-
} else {
44-
return mid;
45-
}
38+
function binarySearch(arr, target) {
39+
let low = 0 // 搜索范围的最低索引
40+
let high = arr.length - 1 // 搜索范围的最高索引
41+
42+
while (low <= high) {
43+
const mid = Math.floor((low + high) / 2) // 中间索引
44+
45+
if (arr[mid] === target) {
46+
return mid // 找到目标元素,返回索引
47+
}
48+
if (arr[mid] < target) {
49+
low = mid + 1 // 目标元素在右半部分,调整搜索范围的最低索引
50+
} else {
51+
high = mid - 1 // 目标元素在左半部分,调整搜索范围的最高索引
4652
}
47-
return -1;
53+
}
54+
55+
return -1 // 目标元素未找到
4856
}
4957

50-
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].binarySearch(2) // 1
58+
// 测试
59+
console.log(binarySearch([1, 2, 3, 4, 5], 0)) // -1
60+
console.log(binarySearch([1, 2, 3, 4, 5], 3)) // 2
5161
```
5262

53-
二分搜索的时间的复杂度为 O(logN)。
54-
55-
63+
二分搜索的时间复杂度为 O(log n),其中 n 是数组的长度。

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /