This article mainly introduces the method of implementing Hill Sort algorithm in PHP, briefly explains the principle of hill sort, and analyzes the concrete operation skill of PHP to realize hill sort by the example form, and needs friends to refer to
In this paper, we describe the method of implementing Hill sort algorithm in PHP. Share to everyone for your reference, as follows:
Although the various programming languages now have their own powerful sort-library functions, these underlying implementations also take advantage of these basic or advanced sorting algorithms.
It is interesting to understand these complex sorting algorithms, and to realize the subtleties of these sorting algorithms ~
Hill sort (Shell sort): The hill sort is based on the insertion sort, except that the insertion sort is adjacent to each other (similar to the case of Chille h=1), while the hill sort is a comparison and replacement of the distance H.
In hill sort a constant factor N, the original array is divided into groups, each group is composed of H elements, there is likely to be extra elements. Of course, each time the cycle, H is also diminishing (h=h/n). The first cycle starts with a subscript of H. One idea of hill sort is that it is divided into groups to sort.
The best way to understand these algorithms is to have a diagram. Let's start with the code.
<?php/** * Hill sort */function shell_sort (array $arr) { //$arr sorted in ascending order $len = count ($arr); $f = 3;//definition factor $h = 1;//minimum is 1 while ($h < $len/$f) { $h = $f * $h + 1;//1, 4,, 121, 364, 1093, ...
} while ($h >= 1) {//Change the array to H ordered for ($i = $h; $i < $len; $i + +) {//insert a[i] into a[i-h], a[i-2*h], a[i-3*h] ... (The key for the algorithm for ($j = $i; $j >= $h; $j-= $h) { if ($arr [$j] < $arr [$j-$h]) { $temp = $arr [$j]; $arr [$j] = $arr [$j-$h]; $arr [$j-$h] = $temp; } Print_r ($arr); Echo ' <br/> '; Open this line of comments, you can see the case of each step being replaced } } $h = Intval ($h/$f); } return $arr;} $arr = Array (9, 1, 4, 6, -3, 2,, 3), $shell = Shell_sort ($arr), echo ' <pre> ';p rint_r ($shell);/* **array ([0] = -3[1] [1[2] = 2[3] [3[4] = 4[5] + 6[6] = 9[7] + 13[8] = 14[9] = 15 [Ten] = 17[11] = 20[12] + 99)) **/
Articles you may be interested in:
PHP uses a custom key to explain how to encrypt and decrypt data
PHP implementation of simple arithmetic calculator function Example explained
Explanation of how to implement the non-fixed number of parameters in Laravel routing