Php insert sorting

Source: Internet
Author: User
: Php insert sorting: 1. directly insert sorting code implementation: Before sorting:; prin

1. Insert the sorting code directly:


  Before sorting:
"; Print_r ($ arr); insertSort ($ arr); echo"
After sorting:
"; Print_r ($ arr); functioninsertSort (& $ arr) {$ len = count ($ arr); // starts from the second record, compare the preceding ordered sequence to find the insert position for ($ I = 1; $ I <$ len; $ I ++) {$ insertData = $ arr [$ I]; // the record to be inserted $ pos = $ I; // Insert position for ($ j = $ I-1; $ j >=0; $ j --) {if ($ arr [$ j]> $ insertData) // if the previous record is greater than the record to be inserted {$ arr [$ j + 1] = $ arr [$ j]; // move the previous record to another subscript $ pos --;} else {break ;}}$ arr [$ pos] = $ insertData; // Insert it to the correct position for echo"
Sorting result: "; print_r ($ arr );}}

2. binary search insert sorting code implementation


  Before sorting:
"; Print_r ($ arr); bsInsertSort ($ arr); echo"
After sorting:
"; Print_r ($ arr); functionbsInsertSort (& $ arr) {$ len = count ($ arr); for ($ I = 1; $ I <$ len; $ I ++) {$ left = 0; $ right = $ I-1; $ mid = 0; $ insertData = $ arr [$ I]; // the record to be inserted while ($ left <= $ right) {$ mid = ($ left + $ right)/2; if ($ insertData> $ arr [$ mid]) {$ left = $ mid + 1;} else {$ right = $ mid-1 ;}} // $ left is the position to insert for ($ j = $ I-1; $ j >=$ left; $ j --) {$ arr [$ j + 1] = $ arr [$ j]; // a number larger than the value of the inserted record.} $ arr [$ left] = $ insertData ;}}

'). AddClass ('pre-numbering '). hide (); $ (this ). addClass ('Has-numbering '). parent (). append ($ numbering); for (I = 1; I <= lines; I ++) {$ numbering. append ($ ('
  • '). Text (I) ;}; $ numbering. fadeIn (1700) ;}) ;}; script

    The above introduces the insert sorting of php, including the insert sorting and php content, and hopes to help friends who are interested in the PHP Tutorial.

    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.