Run Code
|
Code Wall
|
Users
|
Misc
|
Feedback
|
About
|
Login
|
Theme
|
Privacy
PHP - BinarySearch (Find-count-of-an-element)
<?php //php 7.0.8 $data = [1,1,3,3,3,5,5,5,5,5,9,9,11]; $search = 3; findCount($data, $search); function findCount($data, $search) { $firstOccurrence = find($data, $search, true); $lastOccurrence = find($data, $search, false); echo "Count::: ".(($lastOccurrence - $firstOccurrence) + 1); } function find($data, $search, $isFirstOccurrence=true) { $low = 0; $high = sizeof($data) - 1; $result = -1; while($low <= $high) { $mid = $low + (int)(($high-$low)/2); if ($search == $data[$mid]) { $result = $mid; if ($isFirstOccurrence) { $high = $mid - 1; } else{ $low = $mid + 1; } } else if ($search < $data[$mid]) { $high = $mid - 1; } else if ($search > $data[$mid]) { $low = $mid + 1; } } return $result; } ?>
run
|
edit
|
history
|
help
1
Please
log in
to post a comment.
PHP: implode with foreach loops
DEV
PHP trait's execution context
website url validation using php
DEV
Akd
filter array
PHP - SelectionSort
PHP - Stack Implementation
Problem Name: single_digit
Please log in to post a comment.