Description
CDN Search
75CDN jsDelivr
<!DOCTYPE html>
<html>

<head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta charset="utf-8" />
	<title>二分算法示例,针对按顺序排好的索引数组</title>
</head>

<body>
	<pre>
var binarySearch = function (array, start, stop, num) {
    if (stop - start == 1) {
        if (array[start] == num) {
            return start;
        }
        if (array[stop] == num) {
            return stop;
        }
        return -1;
    }
    var center = Math.floor((start + stop) / 2);
    if (num != array[center]) {
        return num > array[center] ? binarySearch(array, center, stop, num)
            : binarySearch(array, start, center, num);
    }
    return center;
}
var array = [1, 4, 6, 12, 15, 20];
document.writeln('result:' + binarySearch(array, 0, array.length, 2));
</pre>
</body>

</html>
var js = document.body.getElementsByTagName('pre')[0].innerText;
(new Function(js))();
pre{
    border: 1px solid #ddd;
    padding: 5px;
}