C++ and PHP Implementation of Binary Search Algorithm

C++ implementation:

 

#include<iostream>
#include<stdlib.h>
#include<algorithm> using namespace std; int Bisection(int key, int arr[], int low, int high) { if(low > high) return -1; int mid = (low + high) / 2; if(key < arr[mid]) return Bisection(key, arr, low, mid - 1); else if(key == arr[mid]) return mid; else return Bisection(key, arr, mid + 1, high); } // It is best to write the test case before writing the algorithm int main() { int n, key, position; cin>>n; int *arr; arr = (int*)calloc(n, sizeof(int)); for(int i = 0; i < n; i++) { cin>>arr[i]; }
   // sort the array
   sort(arr, arr + n); cin
>>key; if((position = Bisection(key, arr, 0, n - 1)) != -1) { cout << " Keyword position: " <<position<< endl; }else { cout << " Keyword not found! " << endl; } // When using dynamic arrays, remember to release the memory at the end free (arr); return 0 ; }

 

PHP implementation:

 

<?php

/**
 * Implementation class
 */
namespace achieve;

class publicMethod
{
    /**
     * @param $key
     * @param $arr
     * @param $low
     * @param $high
     * @return float|int
     * @description implementation method of binary search
     */
    public function Bisection($key, $arr, $low, $high) {
        if ($low > $high) return -1;
        $mid = round(($low + $high) / 2);
        if ($key < (int)$arr[$mid]) return $this->Bisection($key, $arr, $low, $mid - 1);
        else if($key == (int)$arr[$mid]) return $mid;
        else return $this->Bisection($key, $arr, $mid + 1, $high);
    }
}

/**
 * test class
 */
namespace test;
use achieve;

class Test
{
    /**
     * Use case method to test binary search
     */
    public function testBisection() {
        $pm = new \achieve\publicMethod();
        $n = fgets(STDIN);
        $arr = explode(" ", trim(fgets(STDIN)));
        $key = fgets(STDIN);
     sort($arr, SORT_REGULAR); 
        if (( $position = $pm ->Bisection((int) $key , $arr , 0, count ( $arr ) - 1)) != -1 ) {
             fwrite (STDOUT, "Key position is: $position " );
        } else {
             fwrite (STDOUT, "Keyword not found!" );
        }
    }
}

$test = new Test();
$test->testBisection();

?>

 

This PHP code needs to be executed on the command line, use php filepath.php to execute filepath is the full path of the script plus the file name.

 

It is best to write test cases before writing specific algorithm implementations.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339880&siteId=291194637