首页 > 后端开发 > php教程 > [PHP] 看博客学习插入排序

[PHP] 看博客学习插入排序

WBOY
发布: 2016-07-29 08:51:54
原创
965 人浏览过

定义数组长度变量$len,使用count()函数,参数:数组

for循环数组,条件:从第二个开始,遍历数组,循环内

         定义临时变量$temp,赋值当前元素

         for循环数组,条件:遍历当前元素前面的所有元素

         判断当前元素与它前面的元素的大小,利用临时变量,转换变量

[PHP] 看博客学习插入排序

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教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板