|
|
|
@ -1,6 +1,6 @@
@@ -1,6 +1,6 @@
|
|
|
|
|
## 实现一个基于二分查找的整形数组查找 |
|
|
|
|
|
|
|
|
|
```javascript |
|
|
|
|
```typescript |
|
|
|
|
const indexOf_BinarySearch = (dataArr: number[], num: number): number => { |
|
|
|
|
let n1 = 0; |
|
|
|
|
let n2 = dataArr.length - 1; |
|
|
|
@ -8,14 +8,14 @@ const indexOf_BinarySearch = (dataArr: number[], num: number): number => {
@@ -8,14 +8,14 @@ const indexOf_BinarySearch = (dataArr: number[], num: number): number => {
|
|
|
|
|
if (n2 === num) return n2; |
|
|
|
|
|
|
|
|
|
while (n1 <= n2) { |
|
|
|
|
const mid = Math.floor((n1 + n2) / 2); |
|
|
|
|
if (num > dataArr[mid]) { |
|
|
|
|
n1 = mid + 1; |
|
|
|
|
} else if (num < dataArr[mid]) { |
|
|
|
|
n2 = mid - 1; |
|
|
|
|
} else { |
|
|
|
|
return mid; |
|
|
|
|
} |
|
|
|
|
const mid = Math.floor((n1 + n2) / 2); |
|
|
|
|
if (num > dataArr[mid]) { |
|
|
|
|
n1 = mid + 1; |
|
|
|
|
} else if (num < dataArr[mid]) { |
|
|
|
|
n2 = mid - 1; |
|
|
|
|
} else { |
|
|
|
|
return mid; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
return -1; |
|
|
|
|