Home > Article > Backend Development > PHP sorting: Algorithmic idea and algorithm implementation of PHP insertion sort
The content of this article is about PHP sorting: the algorithm idea and algorithm implementation of PHP insertion sort. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Algorithm introduction:
Here we still use an example from "Dahua Data Structure":
Poker is something that almost everyone of us has played. game. Usually when we start, one person deals the cards, and everyone else draws and sorts the cards. If the first card you draw is 5 and the second card is 3, naturally we insert the 3. Go to the front of 5; the third card is 4, find it between 3 and 5; the fourth card is 6, put it behind 5; the fifth card is 2, insert it in front of 3;…. Finally, when we have drawn all the cards, the cards in our hands are sorted from small to large (points).
Let’s look at this sequence:
5 to 5 In the order of 5,
3 4 5 6 // Insert 6 into the order of two elements 3 4 5,
3 4 5 6 2 // Insert 2 Entering two elements 3 4 5 5 In the ordered list of 6
2 3 4 5 6
// 直接插入排序 function swap(&$arr,$a,$b) { $temp = $arr[$a]; $arr[$a] = $arr[$b]; $arr[$b] = $temp; } function insertSort(&$arr) { $count = count($arr); for ($i=1; $i = 0 && $arr[$j] > $temp;$j--) { $arr[$j + 1] = $arr[$j]; //记录后移 } $arr[$j + 1] = $temp; //插入到正确的位置 } } $arr = array(9,1,5,8,3,7,4,6,2); insertSort($arr); var_dump($arr);Running result:
array(9) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[ 4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7] =>
int(8)
[8]=>
int(9)
}
php array sorting method sharing (bubble sort, selection sort)
The above is the detailed content of PHP sorting: Algorithmic idea and algorithm implementation of PHP insertion sort. For more information, please follow other related articles on the PHP Chinese website!