search
HomeBackend DevelopmentPHP TutorialPHP half (two points) search algorithm example analysis php skills

This article mainly introduces the PHP half (two-point) search algorithm. It analyzes the concept, principle, implementation and usage of the PHP half-half (two-point) search algorithm in detail in the form of examples. It also comes with a PHP half (two-point) search algorithm. ) Search algorithm class for your reference. Friends who need it can refer to

. The example in this article describes the PHP half (bisection) search algorithm. Share it with everyone for your reference, the details are as follows:

Half query is only applicable to arrays, strings, etc. that have been sorted in positive or reverse order;

Algorithm:

First take the middle position of the array, if there is no middle position, then round down;

Fold it in half from the middle, judge the size, and enter the first half or the second half;

then Perform the same half-and-half query on the first half or the second half,

will not stop until the matching character is found (in this example, break is used, if it is placed in a function, just return)

The code implemented by php is as follows:

<?php
$arr = array(1,2,3,4,5,6,7,8,9,10);//数组
$key = 4;//要查询的关键字
$low = 0;//开始位的标志
$high = count($arr);//终止位的标志
while($low <= $high){//查询开始结束的条件
 $mid = floor(($low + $high)/2);//进行中间位置计算,向下取整
 if($arr[$mid] == $key){//查询成功
 echo $arr[$mid];
 break;//结束本页执行,函数可用return
 }elseif($arr[$mid] > $key){ //查询前半段,把结束标志移到中间位置前一位
 $high = $mid - 1;
 }else{ //查询后半段,把开始位置移到中间位置的后一位
 $low = $mid + 1;
 }
}
/*
运行结果:4
*/
?>

##Additional: Halving (bisection) search algorithm class:

/**
 * Description:php实现二分查找算法的类
 * @author wzy
 */
class binary_search{
  public $arr;
  public $key;
  function __construct($arr,$key){
    //这里初始化的数组已经是有序数组
    $this->arr=$arr;
    $this->key=$key;
  }
  function binarysearch(){
    $start=0;
    $end=count($this->arr)-1;
    while($start<=$end){
      //mid的取值可以为上整数或者下整数
      $mid=ceil(($start+$end)/2);
      //$mid=($start+$end)>>1;
      //$mid=intval(($start+$end)/2);
      if($this->arr[$mid]<$this->key){
        $start=$mid+1;
      }else if($this->arr[$mid]>$this->key){
        $end=$mid-1;
      }else{
        return $mid;
      }
    }
  }
}

You may also encounter this situation. The elements in the array have duplicate data, and the first one in the duplicate data needs to be returned. The position of an element, for example

$arr=array(1,2,3,4,5,6,6,6,6,7,8);

When searching for the element 6, the position returned should be 5, not others (the subscript starts counting from 0), so It needs to be judged on the returned mid. The code is as follows:

/**
 * Description:php实现二分查找算法的类
 * @author wzy
 */
class binary_search{
  public $arr;
  public $key;
  function __construct($arr,$key){
    //这里初始化的数组已经是有序数组
    $this->arr=$arr;
    $this->key=$key;
  }
  function binarysearch(){
    $start=0;
    $end=count($this->arr)-1;
    while($start<=$end){
      //mid的取值可以为上整数或者下整数
      $mid=ceil(($start+$end)/2);
      //$mid=($start+$end)>>1;
      //$mid=intval(($start+$end)/2);
      if($this->arr[$mid]<$this->key){
        $start=$mid+1;
      }else if($this->arr[$mid]>$this->key){
        $end=$mid-1;
      }else{
        //返回第一个匹配的元素
        for($i=$mid-1;$i>=0;$i--){
          if($this->arr[$i]==$this->key){
            $mid=$i;
          }else{
            break;
          }
        }
        return $mid;
      }
    }
  }
}

## Articles you may be interested in:

PHP generates the relevant content of the request signature required by Tencent Cloud COS interface


PHP access database configuration general method (json) Qiao


Explanation on connecting PHP to MySQL database and outputting it in json format


The above is the detailed content of PHP half (two points) search algorithm example analysis php skills. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.