Home>Article>Backend Development> How to implement insertion sort in PHP?

How to implement insertion sort in PHP?

藏色散人
藏色散人 Original
2019-03-06 14:14:07 3863browse

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));

Output:

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

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!

Statement:
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