How to implement insertion sort in PHP?

藏色散人
Release: 2023-04-05 14:16:02
Original
3723 people have browsed it

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) in one go. It is much less efficient on large lists than most advanced algorithms such as quick sort, stack or merge sort.

How to implement insertion sort in PHP?

Graphical example of insertion sort:

How to implement insertion sort in PHP?

PHP insert The sorted code example is as follows:

=0 && $my_array[$j] > $val){
            $my_array[$j+1] = $my_array[$j];
            $j--;
        }
        $my_array[$j+1] = $val;
    }
    return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "原始数组:\n";
echo implode(', ',$test_array );
echo "\n排序后数组 :\n";
print_r(insertion_Sort($test_array));
Copy after login

Output:

原始数组: 3, 0, 2, 5, -1, 4, 1 
排序后数组 : 
Array ( 
[0] => -1 
[1] => 0 
[2] => 1 
[3] => 2 
[4] => 3 
[5] => 4 
[6] => 5 
)
Copy after login

Related recommendations: "PHP Tutorial"

This article This is an introduction to the insertion sort method in PHP. I hope it will be helpful to friends who need it!

The above is the detailed content of How to implement insertion sort in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!