This is a creation in Article, where the information may have evolved or changed.
This algorithm is still my postgraduate examination of the time to read. There are basically two kinds of insertion sort, head interpolation and tail interpolation method. The difference is whether the inserted position is the head or the tail.
Simply say the idea of inserting a sort:
- Starting from the second element, the first element is considered to be orderly;
- The element to be inserted is then sequentially compared to an ordered queue and inserted into the appropriate position;
- Loop execution until the end of the traversal.
Golang the implementation of the package and I said above the strict grandmother's a little different. The traversed elements are compared backwards with the ordered queue in turn. If smaller than the ordered queue, exchange these two elements.
In contrast to traditional methods, the insertion step is also implemented by moving from back to forward. This method is a little simpler and does not need to declare temporary variables.
package mainimport "fmt"func insertionSort(data Interface, a, b int) {for i := a + 1; i < b; i++ {for j := i; j > a && data.Less(j, j-1); j-- {data.Swap(j, j-1)}}}type BySortIndex []intfunc (a BySortIndex) Len() int { return len(a) }func (a BySortIndex) Swap(i, j int) { a[i], a[j] = a[j], a[i] }func (a BySortIndex) Less(i, j int) bool {return a[i] < a[j]}func main() {test0 := []int{49, 38, 65, 97, 76, 13, 27, 49}insertionSort(BySortIndex(test0), 0, len(test0))fmt.Println(test0)}type Interface interface {// Len is the number of elements in the collection.Len() int// Less reports whether the element with// index i should sort before the element with index j.Less(i, j int) bool// Swap swaps the elements with indexes i and j.Swap(i, j int)}
Please refer to the complete source code in this article.