美文网首页
插入排序

插入排序

作者: 天天天向上 | 来源:发表于2017-12-12 17:20 被阅读0次

php实现:

<?php
$arr = [4, 9, 5, 2, 3, 8, 6, 7, 1, 0];
function insertSort($arr) {
    for ($i=1; $i < count($arr); $i++) { 
        $temp = $arr[$i];
        for ($j=$i-1; $j>=0; $j--) { 
            if ($temp < $arr[$j]) {
                $arr[$j+1] = $arr[$j];
                $arr[$j] = $temp;
            } else 
                break;
        }
    }
    return $arr;
}
var_dump(insertSort($arr));

Go实现:

package main

import (
    "fmt"
)

func main() {
    var arr = []int{9, 4, 5, 2, 3, 8, 6, 7, 1, 0}
    insertSort(arr)
    fmt.Println(arr)
}
func insertSort(arr []int) []int {
    count := len(arr)
    for i := 1; i < count; i++ {
        temp := arr[i]
        for j := i - 1; j >= 0; j-- {
            if temp < arr[j] {
                arr[j+1] = arr[j]
                arr[j] = temp
            } else {
                break
            }
        }
    }
    return arr
}

相关文章

网友评论

      本文标题:插入排序

      本文链接:https://www.haomeiwen.com/subject/uqpnixtx.html