十大排序算法之插入排序(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;
上一篇:php机制本身不提供多线程的操作,有了swoole就不一样了


下一篇:Memcached:memcache学习(二)