PHP Data structure (4) direct insertion and sorting

Source: Internet
Author: User
: This article mainly introduces the PHP Data structure (4) direct insertion sorting. if you are interested in the PHP Tutorial, refer to it. Directly inserting and sorting is to insert an element to the sorted array in order of size. assume that an unordered array has N elements, insertion of N-1 times can be sorted.

For example, an unordered array with five elements will be inserted and sorted four times, for example, $ array (, 18)

First time: $ array (15) insert element 7 into the array, after sorting: $ array)

Second: $ array () insert element 43 into the array, sorted: $ array (, 43)

The third time: $ array (, 43) inserts element 22 into the array. after sorting: $ array)

The fourth time: $ array (,) inserts element 18 into the array. after sorting: $ array (7,.,), the sorting is completed.

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 introduces the PHP Data structure (4) direct insertion sorting, including content, hope to be helpful to 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.