1. Home
  2. >
  3. binary search
2

binary search
Peter Kravets Peter Kravets

recursive

# algoritms
<?php

$names = ['Petro', 'oleg', 'zanar', 'yura', 'igor'];

sort($names);

function find($names, $search) {
    $count = count($names);
    
    $half = floor($count / 2);
    $element = $names[$half];
    
    if ($element === $search) return $element;
    if ($count === 1) return false; 
    
    if ($search > $element) {
        return find(array_slice($names, $half), $search);
    } else {
        return find(array_slice($names, 0, $half), $search);
    }

}

echo find($names, 'Petro');

Discussions

# algoritms