首页 > 编程语言 > 详细

十大排序算法之插入排序(3)

时间:2021-02-08 22:22:17      阅读:28      评论:0      收藏:0      [点我收藏+]

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;

十大排序算法之插入排序(3)

原文:https://www.cnblogs.com/qiye5757/p/14390057.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!