PHP implementation binary Query algorithm

Source: Internet
Author: User
PHP implementation binary query algorithm, write their own code, may not be standardized.

What is the binary query algorithm? Specific words describe themselves Baidu. Directly on the code:

 $startIndex) {$searchIndex = Ceil (($endIndex-$startIndex)/2);} else if ($endIndex = = $startIndex) {$searchIndex = $endIndex;} else{$index = -1;break;} $searchIndex + = ($startIndex-1); Echo ' Search range: '. $startIndex. ' ~ ' $endIndex. '
Search location: '. $searchIndex. ' Retrieve value: '. $data [$searchIndex];echo '
=======================

' If ($data [$searchIndex] = = $x) {$index = $searchIndex; break;} else if ($x > $data [$searchIndex]) {$startIndex = $searchIndex + 1;} else{$endIndex = $searchIndex-1;} $number + +;} while ($number < count ($data)); return $index;} /* Binary Query algorithm--use recursive */function ssort ($data, $x, $startIndex, $endIndex) {if ($endIndex > $startIndex) {$searchIndex = Ceil ( $endIndex-$startIndex)/2);} else if ($endIndex = = $startIndex) {$searchIndex = $endIndex;} else{return-1;} $searchIndex + = ($startIndex-1); Echo ' Search range: '. $startIndex. ' ~ ' $endIndex. '
Search location: '. $searchIndex. ' Retrieve value: '. $data [$searchIndex];echo '
=======================

' If ($data [$searchIndex] = = $x) {return $searchIndex;} else if ($x > $data [$searchIndex]) {$startIndex = $searchIndex + 1;return ssort ($data, $x, $startIndex, $endIndex);} else{$endIndex = $searchIndex -1;return ssort ($data, $x, $startIndex, $endIndex);}} $data = Array (1, 3, 4, 6, 9, one, a, a, a, a, a, a, 11, a, A, a), a. $index = QSort ($data); No recursive ordering method $index = Ssort ($data, one, 0, Count ($data)-1); Using recursive sorting methods echo ' Result: '. $index;

The above describes the PHP implementation of the binary query algorithm, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.