- Generally, the time complexity of direct insertion sorting is O (n ^ 2), but when the series are basically ordered, the time complexity will be improved to O (N)
1 <? PHP 2 # specify that all part of the array elements move one 3 function move (array $ arr, $ start = NULL, $ end = NULL) {4 If (! Isset ($ start) | $ start <0) $ start = 0; 5 If (! Isset ($ end) | $ end> = count ($ ARR) $ end = count ($ ARR)-2; # Finally, you can only select 6 for ($ I = $ end; $ I >=$ start; $ I --) {7 $ arr [$ I + 1] = $ arr [$ I]; 8} 9 return $ arr; 10} 11 12 # insert sorting, implement 13 function insertsort (array $ ARR) {14 for ($ I = 1; $ I <count ($ ARR); $ I ++) using the same Array move-Back Method) {# unordered array, starting from the second element 15 $ insertele = $ arr [$ I]; # element to be inserted 16 for ($ J = 0; $ j <$ I; $ J ++) {# sorted array, starting from the first element 17 if ($ arr [$ J]> $ arr [$ I]) {# sort by Ascending Order 18 $ ar R = move ($ arr, $ J, $ I-1 ); # First move all the elements in the sorted array that are larger than the elements to be inserted, and then move one digit 19 $ arr [$ J] = $ insertele; # insert 20 break of the element to be inserted; 21} 22} 23} 24 return $ arr; 25} 26 27 $ arr = array (5, 1, 7, 4, 6, 2 ); 28 $ arr = insertsort ($ ARR); 29 print_r ($ ARR); 30?>
Output:
Array ([0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 6 [5] => 7)
The sorting process is as follows. Red indicates the sorted part.