JavaScript 折半查找字符在数组中的位置(有序列表)

作者:青柠

时间:2026-10-26

浏览:118

本文介绍如何使用 JavaScript 实现折半查找算法,用于在有序数组中定位指定字符的位置。代码通过维护低点和高点指针,计算中间值并逐步缩小搜索范围,最终返回字符索引或-1。适用于已排序的字符串数组场景。

文章目录

JavaScript 折半查找有序数组实现

代码如下:

/** 
* 折半查找字符在数组中的位置(有序列表)
* @param array 被检索的数组
* @param x 要查找的字符
* @type int
* @returns 字符在数组中的位置,没找到返回-1
*/ 
function binarySearch(array, x) {
var lowPoint = 1;
var higPoint = array.length;
var returnValue = -1;
var midPoint;
var found = false;
while ((lowPoint <= higPoint) && (!found)) {
midPoint = Math.ceil((lowPoint + higPoint) / 2);
//console.log(lowPoint+"===="+midPoint+"===="+higPoint);
if (x > array[midPoint - 1]) {
lowPoint = midPoint + 1;
} 
} else if (x < array[midPoint - 1]) {
higPoint = midPoint - 1;
} 
} else if (x === array[midPoint - 1]) {
found = true;
} 
} 
if (found) {
returnValue = midPoint;
} 
return returnValue;
} 
/*var array2=[1,2,3,4,5,6,7,8,9,100,109];*/
var array2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
console.log(binarySearch(array2, 'c'));

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章