Maison >développement back-end >tutoriel php >[PHP] 看博客学习插入排序
定义数组长度变量$len,使用count()函数,参数:数组
for循环数组,条件:从第二个开始,遍历数组,循环内
定义临时变量$temp,赋值当前元素
for循环数组,条件:遍历当前元素前面的所有元素
判断当前元素与它前面的元素的大小,利用临时变量,转换变量
PHP版:
<span>php </span><span>$arr</span>=<span>array</span>(2,3,4,1,5<span>); </span><span>function</span> insert_sort(<span>$arr</span><span>){ </span><span>$len</span>=<span>count</span>(<span>$arr</span><span>); </span><span>for</span>(<span>$i</span>=1;<span>$i</span>$len;<span>$i</span>++<span>){ </span><span>$temp</span>=<span>$arr</span>[<span>$i</span><span>]; </span><span>for</span>(<span>$j</span>=<span>$i</span>-1;<span>$j</span>>=0;<span>$j</span>--<span>){ </span><span>if</span>(<span>$temp</span>$arr[<span>$j</span><span>]){ </span><span>$arr</span>[<span>$j</span>+1]=<span>$arr</span>[<span>$j</span><span>]; </span><span>$arr</span>[<span>$j</span>]=<span>$temp</span><span>; }</span><span>else</span><span>{ </span><span>break</span><span>; } } } </span><span>return</span><span>$arr</span><span>; } </span><span>$arr</span>=insert_sort(<span>$arr</span><span>); </span><span>print_r</span>(<span>$arr</span>);
java版:
<span>package</span><span> com.tsh.mthread; </span><span>public</span><span>class</span><span> Home { </span><span>public</span><span>static</span><span>void</span><span> main(String[] args) { </span><span>int</span>[] arr=<span>new</span><span>int</span>[]{2,3,4,1,5<span>}; arr</span>=<span>insert_sort(arr); </span><span>for</span>(<span>int</span><span> x:arr){ System.out.println(x); } } </span><span>/**</span><span> * 插入排序 * </span><span>@param</span><span> arr * </span><span>@return</span><span>*/</span><span>public</span><span>static</span><span>int</span>[] insert_sort(<span>int</span><span>[] arr) { </span><span>int</span> len=<span>arr.length; </span><span>for</span>(<span>int</span> i=1;i<len>){ <span>int</span> temp=<span>arr[i]; </span><span>for</span>(<span>int</span> j=i-1;j>=0;j--<span>){ </span><span>if</span>(temparr[j]){ arr[j+1]=<span>arr[j]; arr[j]</span>=<span>temp; }</span><span>else</span><span>{ </span><span>break</span><span>; } } } </span><span>return</span><span> arr; } }</span></len>
以上就介绍了[PHP] 看博客学习插入排序,包括了插入排序,php方面的内容,希望对PHP教程有兴趣的朋友有所帮助。