1. Home
  2. >
  3. binary search
0

binary search
Peter Kravets

recursive

<?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');
# algoritms