Php Data structure and algorithm (PHP description) lookup and binary lookup _ PHP Tutorial

Source: Internet
Author: User
Php Data structure and algorithm (PHP description) search and binary search. Copy the code as follows :? Php *** lookup *** sequential lookup functionnormal_search ($ arrData, $ val) {$ lencount ($ arrData); if ($ len0) return-1; for ($ i0; $ I $ len; $ I ++ The code is as follows:


/**
* Search
*
**/
// Sequential search
Function normal_search ($ arrData, $ val ){
$ Len = count ($ arrData );
If ($ len = 0) return-1;
For ($ I = 0; $ I <$ len; $ I ++ ){
Echo "find No.", $ I + 1, "value =", $ arrData [$ I], "is =", $ val ,"?
";
// Found
If ($ arrData [$ I] ==$ val) return $ I;
}
Return-1;
}

// Test order search
$ ArrData = array );
Echo normal_search ($ arrData, 6 ),"
";
Echo normal_search ($ arrData, 66 ),"
";

// Binary search (search for ordered columns)
Function binary_search ($ arrData, $ val ){
$ Len = count ($ arrData );
If ($ len = 0) return-1;

$ Start = 0;
$ End = $ len-1;

While ($ start <= $ end ){
$ Middle = intval ($ start + $ end)/2 );
Echo "start =", $ start, "end =", $ end, "middle =", $ middle ,"
";
If ($ arrData [$ middle] ==$ val ){
Return $ middle;
} Elseif ($ arrData [$ middle]> $ val ){
$ End = $ middle-1;
} Elseif ($ arrData [$ middle] <$ val ){
$ Start = $ middle + 1;
}
}
Return-1;
}

// Test binary search
$ ArrData = array (56,100,104,578,100 );
Echo binary_search ($ arrData, 578 ),"
";
Echo binary_search ($ arrData, 66 ),"
";

The http://www.bkjia.com/PHPjc/325529.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/325529.htmlTechArticle code is as follows :? Php/*** search *** // query function normal_search in sequence ($ arrData, $ val) {$ len = count ($ arrData ); if ($ len = 0) return-1; for ($ I = 0; $ I $ len; $ I ++...

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.