Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.5 kB
14
Indexable
Never
<?php

$arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// 5, 6, 7, 8, 9
// 5, 
// 6
// ,7

$x = 8;


function searchInArray($numbers, $unknown)
{
    if(sizeof($numbers) == 1){
        
        if($numbers[array_key_last($numbers)] == $unknown){
            return array_key_last($numbers);
        }


        return 'paida nashod';
    }

    if(sizeof($numbers) == 0){
        return 'paida nashod';
    }

    $pivot = intval((array_key_first($numbers) + array_key_last($numbers))/2);

    if($numbers[$pivot] > $unknown){

        $startIndex = array_key_first($numbers);

        var_dump($pivot, $startIndex); die();
        
        $endIndex = $pivot;

        return searchInArray(

                // array_values(
                    array_slice(
                        $numbers,
                        $startIndex,
                        $endIndex - $startIndex
                    )
                // )
                ,

                $unknown
            );

    
    }elseif($numbers[$pivot] < $unknown){
    
        $startIndex = $pivot+1;
    
        $endIndex = array_key_last($numbers);

        return searchInArray(

                array_slice(
                    $numbers, 
                    $startIndex, 
                    $endIndex - $startIndex
                )
                ,

                $unknown
            );
    
    }elseif($numbers[$pivot] == $unknown) {
        return $pivot;
    }

}

$result = searchInArray($arrayOfNumbers, $x);

echo $result;

echo PHP_EOL;