PHP实现插入排序

WBOY
Release: 2016-06-23 14:37:26
Original
924 people have browsed it

插入排序的基本操作就是将一个数据插入到已经排好序的有序数据中,从而得到一个新的、个数加一的有序数据。

算法描述:

⒈ 从第一个元素开始,该元素可以认为已经被排序

⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描

⒊ 如果该元素(已排序)大于新元素,将该元素移到下一位置

⒋ 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置

⒌ 将新元素插入到下一位置中

⒍ 重复步骤2

<?php    $arr =array(123,0,5,-1,4,15);    function insertSort(&$arr){        //先默认第一个下标为0的数是排好的数        for($i=1;$i<count($arr);$i++){            //确定插入比较的数            $insertVal=$arr[$i];            //确定与前面比较的数比较            $insertIndex=$i-1;                        //表示没有找到位置            while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){                //把数后移                $arr[$insertIndex+1]=$arr[$insertIndex];                $insertIndex--;            }        //插入(给$insertval找到位置了)        $arr[$insertIndex+1] = $insertVal;        }    }    insertSort($arr);    print_r($arr);?>
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!