zoukankan      html  css  js  c++  java
  • 十大排序算法之插入排序(3)

    3.插入排序

    <?php
    
    /**
     * 基础插入排序
     *
     */
    function insertionSort($sortData)
    {
        $count = count($sortData);
        $sortCount = 0;
        for ($i = 1; $i < $count; $i++) {
            $preIndex = $i - 1;
            $current = $sortData[$i];
            $sortCount++;
            while ($preIndex >= 0 && $current < $sortData[$preIndex]) {
                $sortData[$preIndex + 1] = $sortData[$preIndex];
                $preIndex--;
                $sortCount++;
            }
            $sortData[$preIndex + 1] = $current;
        }
        echo 'insertionSort Count:' . $sortCount;
        echo PHP_EOL;
        return $sortData;
    }
    
    /**
     * 插入排序优化1:可以使用查找算法减少有序序列的查询效率(如2分查找)
     *
     */
    function insertionSort_2($sortData)
    {
        $count = count($sortData);
        $sortCount = 0;
        for ($i = 1; $i < $count; $i++) {
            $current = $sortData[$i];
            $start = binarySearchIndex($sortData, $i - 1, $current, $sortCount);
            for ($j = $i - 1; $j >= $start; $j--) {
                $sortCount++;
                $sortData[$j + 1] = $sortData[$j];
            }
            $sortData[$start] = $current;
        }
        echo 'insertionSort_2 Count:' . $sortCount;
        echo PHP_EOL;
        return $sortData;
    }
    
    function binarySearchIndex($sortData, $end, $compare, &$sortCount)
    {
        $start = 0;
        while ($start <= $end) {
            $sortCount++;
            $middle = intval(($start + $end) / 2);
            if ($sortData[$middle] > $compare) {
                $end = $middle - 1;
            } else {
                $start = $middle + 1;
            }
        }
        return $start;
    }
    
    $testSortData = [3, 2, 9, 234, 3432, 43, 22, 33, 21312, 123];
    
    $sortResult = insertionSort($testSortData);
    echo 'insertionSort Result:';
    echo PHP_EOL;
    echo(implode(',', $sortResult));
    echo PHP_EOL;
    
    $sortResult = insertionSort_2($testSortData);
    echo 'insertionSort_2 Result:';
    echo PHP_EOL;
    echo(implode(',', $sortResult));
    echo PHP_EOL;
  • 相关阅读:
    DHCP服务器
    继承、抽象、多态
    范围随机数Random
    阿里、北理工、清华以及华为的镜像站
    创建kafka生产对象
    kafka消费者的配置
    Kafka 流数据 SQL 引擎 -- KSQL
    认证maven工程
    基础算法
    Java基础
  • 原文地址:https://www.cnblogs.com/qiye5757/p/14390057.html
Copyright © 2011-2022 走看看