Home Backend Development PHP Tutorial PHP 常见算法【冒泡排序, 快速排序, 插入排序, 取舍排序, 二分法查找, .】

PHP 常见算法【冒泡排序, 快速排序, 插入排序, 取舍排序, 二分法查找, .】

Jun 13, 2016 pm 01:17 PM
arr array count return start

PHP 常见算法【冒泡排序, 快速排序, 插入排序, 选择排序, 二分法查找, ..】

// 冒泡排序
function bubblesort($arr) {
    for($i=0,$j=count($arr); $i<$j; $i++) {
        for($k=$j-1; $k>$i; $k--) {
            if ($arr[$k] < $arr[$k-1]) list($arr[$k-1], $arr[$k]) = array($arr[$k], $arr[$k-1]);
        } 
    }
    return $arr;
}

$arr = array(1,4,14,3,56,23,435,2,234,2,33,23,123);
print_r(bubblesort($arr));
Copy after login
// 快速排序
function quicksort($arr) {
    if(($count = count($arr)) <= 1 ) return $arr;
    $base = $arr[0];
    $left = $right = array();
    for($i=1; $i<$count; $i++) {
        if($arr[$i] <= $base) $left[] = $arr[$i];
        else $right[] = $arr[$i];
    }
    $left = quicksort($left);
    $right = quicksort($right);
    return array_merge($left, array($base), $right);
}

echo join(',', quicksort(array(1,3,23,5,234,65,6)));?
Copy after login
// 插入排序
function insertsort($arr) {
    for($i=1, $j=count($arr); $i<$j; $i++) {
        $k = $i;
        while($k > 0 && $arr[$k-1] > $arr[$k]) {
            list($arr[$k], $arr[$k-1]) = array($arr[$k-1], $arr[$k]);
            $k--;
        }
    }
    return $arr;
}

$array=array(10,8,7,5,1,2,3,4);
print_r(insertsort($array));
Copy after login

?

// 选择排序, (非递归)
function selectsort($arr) {
    for($i=0, $j=count($arr); $i<=$j; $i++) {
        $min = $i;
        $temp = $arr[$i];
        for($k=$i+1; $k<$j; $k++) {
            if($temp > $arr[$k]) {
                $min = $k;
                $temp = $arr[$k];
            }
        } 
        if($min != $i) list($arr[$min], $arr[$i]) = array($arr[$i], $arr[$min]);
    }
    return $arr;
}

$arr = array(9,3,11,23,90,99,12,34,22,87,32);
print_r(selectsort($arr));
Copy after login

?

// 选择排序(递归实现)
function selectsort2($arr, $start = 0) {
    if(($count = count($arr)) == $start + 1) return $arr;
    $new = array();
    $min = $arr[$start];
    $min_index = $start;
    for($i=$start+1; $i<$count-1; $i++) {
        if($arr[$i] < $min) {
            $min = $arr[$i];
            $min_index = $i;
        }
    }
    if($arr[$start] != $min) list($arr[$start], $arr[$min_index]) = array($arr[$min_index], $arr[$start]);
    return selectsort($arr, $start + 1);
}
$arr = array(9,3,11,23,90,99,12,34,22,87,32);
print_r(selectsort($arr));
Copy after login
?

?

?

<?php
// 二分法查找
function binarysearch($arr, $value, $start = 0, $end = NULL) {
    if($end == NULL) $end = count($arr) - 1;
    $index = floor(($start+$end)/2);
    $base = $arr[$index];
    if($value < $base) return binarysearch($arr, $value, $start, $index-1);
    else if($value > $base) return binarysearch($arr, $value, $index+1, $end);
    else return $index;
}

$arr = array(1, 3, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20);
$value = 8;
echo binarysearch($arr, $value);
Copy after login
?

待续...

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What should I do if docker start cannot start? What should I do if docker start cannot start? Oct 21, 2022 pm 03:43 PM

Solution to docker start failure: 1. Check the running status, and then release the occupied memory through the "echo 3 &gt; /proc/sys/vm/drop_caches" command; 2. Use "$netstat -nltp|grep .. ." command to check whether the port has been occupied. If it is found to be occupied after going online, change it to an available port and restart.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

The difference between counta and count The difference between counta and count Nov 20, 2023 am 10:01 AM

The Count function is used to count the number of numbers in a specified range. It ignores text, logical values, and null values, but counts empty cells. The Count function only counts the number of cells that contain actual numbers. The CountA function is used to count the number of non-empty cells in a specified range. It not only counts cells containing actual numbers, but also counts the number of non-empty cells containing text, logical values, and formulas.

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

How to use the array_combine function in PHP to combine two arrays into an associative array How to use the array_combine function in PHP to combine two arrays into an associative array Jun 26, 2023 pm 01:41 PM

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values ​​of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

Simple and clear method to use PHP array_merge_recursive() function Simple and clear method to use PHP array_merge_recursive() function Jun 27, 2023 pm 01:48 PM

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values ​​of the same keys, making the program design more flexible. array_merge

What to do if node start reports an error What to do if node start reports an error Dec 29, 2022 pm 01:55 PM

Solution to node start error: 1. Execute "node xx.js" directly in the terminal; 2. Add start startup item "scripts": {"test": "echo \"Error: no test specified\" && exit 1 ","start":"node service.js"}"; 3. Re-execute "npm start".

See all articles