Files
hello-algo/ru/codes/javascript/chapter_searching/binary_search_edge.js
Yudong Jin 71a773df64 fix(ru): align proofreading corrections with the Simplified Chinese original (#2004)
* docs(ru): correct proofreading issues in prose and code examples

* docs(ru): align proofreading edits with Simplified Chinese source

* fix(ru): repair generated Zig statements and complete comment translations
2026-10-27 18:19:11 +08:00

46 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: binary_search_edge.js
* Created Time: 2023-08-22
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
const { binarySearchInsertion } = require('./binary_search_insertion.js');
/* Двоичный поиск самого левого элемента target */
function binarySearchLeftEdge(nums, target) {
// Эквивалентно поиску точки вставки target
const i = binarySearchInsertion(nums, target);
// target не найден, вернуть -1
if (i === nums.length || nums[i] !== target) {
return -1;
}
// target найден, возвращается индекс i
return i;
}
/* Двоичный поиск самого правого элемента target */
function binarySearchRightEdge(nums, target) {
// Преобразовать задачу в поиск самого левого target + 1
const i = binarySearchInsertion(nums, target + 1);
// j указывает на самый правый target, а i — на первый элемент больше target
const j = i - 1;
// target не найден, вернуть -1
if (j === -1 || nums[j] !== target) {
return -1;
}
// target найден, возвращается индекс j
return j;
}
/* Driver Code */
// Массив с повторяющимися элементами
const nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
console.log('\nМассив nums = ' + nums);
// Двоичный поиск левой и правой границы
for (const target of [6, 7]) {
let index = binarySearchLeftEdge(nums, target);
console.log('Индекс самого левого элемента ' + target + ' равен ' + index);
index = binarySearchRightEdge(nums, target);
console.log('Индекс самого правого элемента ' + target + ' равен ' + index);
}