Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,987 questions

51,931 answers

573 users

How to find the nearest smaller element on left side of each element of an array in PHP

1 Answer

0 votes
function smaller_index($arr, $pos) {
    $index = -1;
        
    for ($i = $pos - 1; $i >= 0 && $index == -1; $i--) {
        if ($arr[$i] < $arr[$pos]) {
            $index = $i;
        }
    }
    return $index;
}
function nearest_smaller($arr) {
    $index = 0;
    $size = count($arr);
           
    for ($i = 0; $i < $size; $i++) {
        $index = smaller_index($arr, $i);
        
        if ($index == -1) {
            echo $arr[$i] . " : No Smaller\n";
        }
        else  {
            echo $arr[$i] . " : " . $arr[$index] . "\n";
        }
    }
}

$arr = array(4, 6, 2, 8, 6, 1, 9, 12, 3, 20, 18, 30);
nearest_smaller($arr);

   
   
   
/*
run:
    
4 : No Smaller
6 : 4
2 : No Smaller
8 : 2
6 : 2
1 : No Smaller
9 : 1
12 : 9
3 : 1
20 : 3
18 : 3
30 : 18
    
*/

 



answered Dec 20, 2021 by avibootz
...