Home  >  Article  >  Backend Development  >  PHP插入排序实现代码_PHP教程

PHP插入排序实现代码_PHP教程

WBOY
WBOYOriginal
2016-07-21 15:12:33576browse

算法描述:

⒈ 从第一个元素开始,该元素可以认为已经被排序
⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描
⒊ 如果该元素(已排序)大于新元素,将该元素移到下一位置
⒋ 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
⒌ 将新元素插入到下一位置中
⒍ 重复步骤2

复制代码 代码如下:

    $arr =array(123,0,5,-1,4,15);

    function insertSort(&$arr){

        //先默认第一个下标为0的数是排好的数
        for($i=1;$i            //确定插入比较的数
            $insertVal=$arr[$i];
            //确定与前面比较的数比较
            $insertIndex=$i-1;

            //表示没有找到位置
            while($insertIndex>=0 && $insertVal

                //把数后移
                $arr[$insertIndex+1]=$arr[$insertIndex];
                $insertIndex--;
            }

        //插入(给$insertval找到位置了)
        $arr[$insertIndex+1] = $insertVal;
        }
    }

    insertSort($arr);
    print_r($arr);
?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/326682.htmlTechArticle算法描述: ⒈ 从第一个元素开始,该元素可以认为已经被排序 ⒉ 取出下一个元素,在已经排序的元素序列中从后向前扫描 ⒊ 如果该元素...
Statement:
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