Home > php教程 > php手册 > body text

PHP中实现冒泡排序和快速排序算法示例

WBOY
Release: 2016-05-26 08:20:16
Original
1182 people have browsed it

冒泡排序和快速排序算法在开发应用中各有优点了,下面我们来看几个关于php排序的几个例子.

使用PHP描述冒泡排序和快速排序算法,对象可以是一个数组。

使用PHP描述顺序查找和二分查找,也叫做折半查找算法,顺序查找必须考虑效率,对象可以是一个有序数组.

写一个二维数组排序算法函数,能够具有通用性,可以调用php内置函数.

1.使用PHP描述冒泡排序和快速排序算法,对象可以是一个数组,代码如下:

function bubble_sort($array) {
    $count = count($array);
    if ($count <= 0) return false;
    for ($i = 0; $i < $count; $i++) {
        for ($j = $count - 1; $j > $i; $j & ndash;) {
            if ($array[$j] < $array[$j - 1]) {
                $tmp = $array[$j];
                $array[$j] = $array[$j - 1];
                $array[$j - 1] = $tmp;
            }
        }
    }
    return $array;
}
function quick_sort($array) {
    if (count($array) <= 1) return $array;
    $key = $array[0];
    $left_arr = $right_arr = array();
    foreach ($array as $val) {
        if ($val < = $key) $left_arr[] = $val;
        else $right_arr[] = $val;
    }
    $left_arr = quick_sort($left_arr);
    $right_arr = quick_sort($right_arr);
    return array_merge($left_arr, array(
        $key
    ) , $right_arr);
}
Copy after login

2.使用PHP描述顺序查找和二分查找, 也叫做折半查找算法, 顺序查找必须考虑效率, 对象可以是一个有序数组, 代码如下:

function bin_sch($array, $low, $high, $k) {
    if ($low <= $high) {
        $mid = intval(($low + $high) / 2);
        if ($array[$mid] == $k) {
            return $mid;
        } elseif ($k < $array[$mid]) {
            return bin_sch($array, $low, $mid - 1, $k);
        } else {
            return bin_sch($array, $mid + 1, $high, $k);
        }
    }
    return -1;
}
function seq_sch($array, $n, $k) {
    $array[$n] = $k;
    for ($i = 0; $i < $n; $i++) {
        if ($array[$i] == $k) {
            break;
        }
    }
    if ($i < $n) {
        return $i;
    } else {
        return -1;
    }
}
Copy after login

3.写一个二维数组排序算法函数, 能够具有通用性, 可以调用php内置函数, 代码如下:

function array_sort($arr, $keys, $order = 0) {
    if (!is_array($arr)) {
        return false;
    }
    $keysvalue = array();
    foreach ($arr as $key => $val) {
        $keysvalue[$key] = $val[$keys];
    }
    if ($order == 0) {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $key => $vals) {
        $keysort[$key] = $key;
    }
    $new_array = array();
    foreach ($keysort as $key => $val) {
        $new_array[$key] = $arr[$val];
    }
    return $new_array;
}
Copy after login


本文地址:

转载随意,但请附上文章地址:-)

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template