Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
提交
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@
* [Interpolation搜索](搜索/Interpolation搜索.js)
* [Jump搜索](搜索/Jump搜索.js)
* [Linear搜索](搜索/Linear搜索.js)
* [MetaBinary搜索](搜索/MetaBinary搜索.js)
* [Minesweeper](搜索/Minesweeper.js)
* [QuickSelect搜索](搜索/QuickSelect搜索.js)
* [RabinKarp](搜索/RabinKarp.js)
Expand All @@ -322,8 +323,8 @@
* [Ternary搜索](搜索/Ternary搜索.js)
* [UnionFind](搜索/UnionFind.js)
* **Sliding-Windows**
* [MaxSumSubarrayFixed](Sliding-Windows/MaxSumSubarrayFixed.js)
* [LongestSubarrayWithSumAtMost](Sliding-Windows/LongestSubarrayWithSumAtMost.js)
* [MaxSumSubarrayFixed](Sliding-Windows/MaxSumSubarrayFixed.js)
* **Sorts**
* [AlphaNumericalSort](Sorts/AlphaNumericalSort.js)
* [BeadSort](Sorts/BeadSort.js)
Expand Down
28 changes: 28 additions & 0 deletions 搜索/MetaBinary搜索.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Meta Binary 搜索
* https://www.geeksforgeeks.org/meta-binary-search-one-sided-binary-search/
*
* Builds the index bit by bit from the most-significant bit to the least-significant bit.
* Works on sorted arrays and returns the index of target, or -1 if not found.
*/

function metaBinary搜索(sortedArray, target) {
if (!Array.isArray(sortedArray) || sortedArray.length === 0) {
return -1
}

const n = sortedArray.length
const maxBit = Math.floor(Math.log2(Math.max(1, n - 1)))

let position = 0
for (let bit = maxBit; bit >= 0; bit--) {
const candidate = position + 2 ** bit
if (candidate < n && sortedArray[candidate] <= target) {
position = candidate
}
}

return sortedArray[position] === target ? position : -1
}

export { metaBinary搜索 }
28 changes: 28 additions & 0 deletions 搜索/test/MetaBinary搜索.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { metaBinary搜索 } from '../MetaBinary搜索'

describe('Meta Binary 搜索', () => {
test('returns index for found numeric element', () => {
expect(metaBinary搜索([2, 5, 8, 12, 16, 23, 38], 23)).toBe(5)
})

test('returns -1 when numeric element is missing', () => {
expect(metaBinary搜索([2, 5, 8, 12, 16, 23, 38], 9)).toBe(-1)
})

test('works with sorted strings', () => {
expect(metaBinary搜索(['alpha', 'beta', 'delta', 'omega'], 'delta')).toBe(
2
)
})

Comment thread
nickzerjeski marked this conversation as resolved.
test('returns index for a matching element in a single-element array', () => {
expect(metaBinary搜索([7], 7)).toBe(0)
})
test('returns -1 on empty input', () => {
expect(metaBinary搜索([], 1)).toBe(-1)
})

test('returns index for a matching element in a single-element array', () => {
expect(metaBinary搜索([7], 7)).toBe(0)
})
})
Loading