PHP bubble sorting and binary lookup _ PHP Tutorial

Source: Internet
Author: User
PHP bubble sorting and binary searching for instances. We learned the bubble sort and binary search sort algorithms when we were in junior high school. next I will introduce some examples of the bubble sort and binary search in PHP. We learned how to sort by the code bubble method and the binary search sorting algorithm in junior high school. next I will introduce the examples of sorting by the PHP bubble method and the binary search.

The code is as follows:

// Sort by bubble
// Random array
$ Arr = array (89,112,321,234 );
// Statistics array
$ Num = count ($ arr );
// Bubble sort in reverse order
For ($ I = 0; $ I <$ num-1; $ I ++ ){
For ($ m = 0; $ m <$ num-1; $ m ++ ){
If ($ arr [$ m] <$ arr [$ m + 1]) {
$ Temp = $ arr [$ m];
$ Arr [$ m] = $ arr [$ m + 1];
$ Arr [$ m + 1] = $ temp;
}
// Echo $ arr [$ m].'
';
}
}
// Output the sorted result
Var_dump ($ arr );
// Bubble sequence
For ($ x = 0; $ x <$ num-1; $ x ++ ){
For ($ y = 0; $ y <$ num-1; $ y ++ ){
If ($ arr [$ y]> $ arr [$ y + 1]) {
$ Temp = $ arr [$ y];
$ Arr [$ y] = $ arr [$ y + 1];
$ Arr [$ y + 1] = $ temp;
}
}
}
// Output the sorted result
Var_dump ($ arr );
// Binary search
Function dichotomy ($ array, $ k, $ low = 0, $ high = 0 ){
If (count ($ array )! = 0 & $ high = 0 ){
$ High = count ($ array );
}
If ($ low <= $ high ){
$ Mid = intval ($ low + $ high)/2 );
If ($ array [$ mid] === k ){
Return $ mid;
} Elseif ($ k <$ array [$ mid]) {
Return dichotomy ($ array, $ k, $ low = 0, $ mid-1 );
} Else {
Return dichotomy ($ array, $ k, $ mid + 1, $ high );
}
} Else {
Return false;
}
}
// Output the search result
Echo dichotomy ($ arr, 23 );

Today, I briefly studied the most common sorting and binary lookup of the bubble method, and wrote a simple case to enhance my learning of php.

It also hopes to provide a little help for future php learners.

Bytes. Code...

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.