Principle
Direct insertion of sorting is also a very simple sorting algorithm.
The first round starts with the second element, and the first compares, if smaller, the swap position, the end of this round. The second round starts with the third element, compared with the second one, if smaller is the second interchange, and then the first comparison. This loops until the last element completes the comparison logic.
Complexity of
In the best case, the direct insertion of the sort requires only a n-1 comparison, 0 times of exchange. The average time complexity is O (n^2).
Because each element is compared to an ordered queue, elements that do not appear to have the same numeric value swap positions after sorting is complete. So the direct insert sort is a stable sorting algorithm.
Code
package mainimport ( "fmt" "math/rand")func main() { var length = 10 var tree []int for i := 0; i < length; i++ { tree = append(tree, int(rand.Intn(1000))) } fmt.Println(tree) for i := 1; i < length; i++ { for j := i; j > 0 && tree[j] < tree[j-1]; j-- { tree[j], tree[j-1] = tree[j-1], tree[j] } fmt.Println(tree) }}
Run results