Insertion sort

Insertion sort is a sorting algorithm that constructs an array one item at a time until it results in a sorted array. It's not very efficient, but it does have a simple implementation and is quick for very small datasets. The array is sorted in place, which can also help reduce the memory footprint of the function call.

This standard library algorithm for insertionSort can be found in the following code snippet. We can use the following code snippet to deduce that insertion sort is an average case of an O(n2) algorithm. This is due to the fact that we iterate through a 2D array and manipulate data:

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)
}
}
}

This code can be found in the standard library at https://golang.org/src/sort/sort.go#L183. A simple insertion sort is often valuable for small datasets because it is very easy to read and comprehend. Simplicity often outweighs everything else when it comes to writing performant code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181