PHP data Structure (4) Direct Insert Sort

Source: Internet
Author: User
The direct insertion sort is to insert an ordered element into an already sorted array in the order of size, assuming an unordered array of n elements, the N-1 will be inserted to complete the sorting.

For example, an unordered array with 5 elements, which will be sorted 4 times, such as: $array (15,7,43,22,18)

First time:: $array (15) Insert element 7 into the array, sorted by: $array (7,15)

Second time: $array (7,15) inserts element 43 into the array after sorting: $array (7,15,43)

Third time: $array (7,15,43) inserts element 22 into the array, sorted: $array (7,15,22,43)

Fourth time: $array (7,15,22,41) Inserts element 18 into the array, sorted: $array (7,.15,18,22,43), complete the sort.

The code is implemented as follows:

 $array [$i]) {$temp = $array [$i]; $j = $i; while ($j >0 && $array [$j -1]> $temp) {$array [$j]= $array [$j-1]; $j--;} $array [$j]= $temp;}} return $array;} $arr =array (4,1,17,9,88,37,43), $res =insert_sort ($arr), foreach ($res as $key + = $values) {echo "key:". ( $key + 1). "Value:" $values. " 
";}?

 

The above describes the PHP data structure (4) Direct insertion of the sort, including the content, I hope 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.