Бинарный поиск против перебора (тупого поиска)

Benchmark created on


Setup

const arr = new Array(1000000)

for (let i=0; i < arr.length; i++) {
	arr[i] = i + 1;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Перебор
function searchElement(arr, el) {
	for(let i = 0; i < arr.length; i++) {
		if (arr[i] === el) {
			return i
		}
	}
	return -1
}


const el = Math.floor(Math.random() * arr.length);
searchElement(arr, el)
ready
Бинарный поиск
function searchBinar(nums, target) {
    let left = -1;
    let right = nums.length;

    while (right - left > 1) {
        let mid = Math.floor((right + left) / 2);

        if (target == nums[mid]) {
            return mid;
        }

        if (target > nums[mid]) {
            left = mid;
        } else {
            right = mid;
        }
    }
    
    return -1
};


const el = Math.floor(Math.random() * arr.length);
searchBinar(arr, el)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.