rrylee
10/27/2015 - 2:15 AM

4中排序 冒泡,快排,插入,希尔,归并

4中排序 冒泡,快排,插入,希尔,归并

<?php

function bubble_sort($arr)
{
    $count = count($arr);

    if ($count <= 1) return $arr;

    for ($i = 0; $i < $count; $i ++) {
        for ($j = $i + 1; $j < $count; $j ++) {
            if ($arr[$i] > $arr[$j]) {
                $temp = $arr[$i];
                $arr[$i] = $arr[$j];
                $arr[$j] = $temp;
            }
        }
    }

    return $arr;
}

function quick_sort($arr)
{
    $count = count($arr);

    if ($count <= 1) return $arr;

    $temp = $arr[0];
    $left = array();
    $right = array();

    for ($i = 1; $i < $count; $i ++) {
        if ($temp > $arr[$i])
            $left[] = $arr[$i];
        else
            $right[] = $arr[$i];
    }

    $left = quick_sort($left);
    $right = quick_sort($right);

    return array_merge($left, [$temp], $right);
}

function insert_sort($arr)
{
    $count = count($arr);

    if ($count <= 1) return $arr;

    for ($i = 1; $i < $count; $i ++) {
        $temp = $arr[$i];

        for ($j = $i - 1; $j >= 0; $j --) {
            if ($temp < $arr[$j]) {
                $arr[$j + 1] = $arr[$j];
                $arr[$j] = $temp;
            } else {
                break;
            }
        }
    }

    return $arr;
}

function shell_sort($arr)
{
    $count = count($arr);
    $gap = $count / 2;

    if ($count <= 1) return $arr;

    while ($gap >= 1) {
        for ($i = $gap; $i < $count; $i ++) {
            $temp = $arr[$i];

            for ($j = $i - $gap; $j >= 0 and $temp < $arr[$j]; $j -= $gap) {
                $arr[$j + $gap] = $arr[$j];
            }

            $arr[$j + $gap] = $temp;
        }
        $gap >>= 1;
    }

    return $arr;
}

function mergeSort(&$array, $low, $high) {
    $mid = floor(($low + $high) / 2);
    if ($low < $high) {
        mergeSort($array, $low, $mid);
        mergeSort($array, $mid + 1, $high);
        merge($array, $low, $mid, $high);
    }
}

function merge(&$array, $low, $mid, $high) {
    $temp = [];
    $i = $low;
    $j = $mid + 1;
    $k = 0;

    while ($i <= $mid && $j <= $high) {
        if ($array[$i] < $array[$j]) {
            $temp[$k ++] = $array[$i ++];
        } else {
            $temp[$k ++] = $array[$j ++];
        }
    }

    while ($i <= $mid) {
        $temp[$k++] = $array[$i ++];
    }
    while ($j <= $high) {
        $temp[$k++] = $array[$j ++];
    }

    for ($k2=0; $k2 < count($temp); $k2++) {
        $array[$k2 + $low] = $temp[$k2];
    }
}