<?php
function binarySearch(array $arr, int $target): int
{
$low = 0;
$high = count($arr) - 1;
while ($low <= $high) {
// compute middle index
$mid = floor(($low + $high) / 2);
if ($arr[$mid] > $target) {
// search the left side of the array
$high = $mid -1;
} else if ($arr[$mid] < $target) {
// search the right side of the array
$low = $mid + 1;
} else {
// element found at mid
return $mid;
}
}
// If we reach here element x doesnt exist
return -1;
}
// Driver code
$arr = [1, 2, 3, 4, 5];
$target = 3;
$result = binarySearch($arr, $target);
if($result !== -1) {
echo "Target '$target' exists at position $result";
} else {
echo "Target '$target' does not exist";
}
Double search is a search method used to find an element in a sorted array.
0 Burnfires
0
<?php
function quickSort(array $array): array
{
$length = count($array);
if ($length <= 1) {
return $array;
}
$pivot = $array[0];
$left = $right = [];
for ($i = 1; $i < $length; $i++) {
if ($array[$i] < $pivot) {
$left[] = $array[$i];
} else {
$right[] = $array[$i];
}
}
return array_merge(quickSort($left), [$pivot], quickSort($right));
}
// Example usage:
$array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
$sortedArray = quickSort($array);
echo "Original Array: " . implode(", ", $array) . "\n";
echo "Sorted Array: " . implode(", ", $sortedArray) . "\n";
Here's a simple implementation of the Quick Sort algorithm in PHP
1 Burnfires
0
Snippets46
Categories0
Tags62
Users3