33
loading...
This website collects cookies to deliver better user experience
func insertionSort(arr []int) []int {
for i := 0; i < len(arr); i++ {
for j := i; j > 0 && arr[j-1] > arr[j]; j-- {
arr[j], arr[j-1] = arr[j-1], arr[j]
}
}
return arr
}
<small id="shcb-language-1"><span>Code language:</span> <span>Go</span> <span>(</span><span>go</span><span>)</span></small>
insertionSort()
function starts by iterating over the entire slice in a nested for loop. The job of the inner for loop is to consume one value for each repetition, and grow the sorted output list, which are all the elements before index i
. At each repetition, insertion sort removes one element from the input data, finds the location it belongs within the sorted first section, and inserts it there. It repeats until no input elements remain.func main() {
fmt.Println(insertionSort([]int{5,3,2,1,0,4))
// prints
// [0, 1, 2, 3, 4, 5]
}
<small id="shcb-language-2"><span>Code language:</span> <span>Go</span> <span>(</span><span>go</span><span>)</span></small>
O(n^2)
, because that is its worst-case complexity. The outer loop of insertion sort executes n
times, while the inner loop depends on the input. In the worst case (a reverse sorted array) the inner loop executes n
times as well. In the best case (a sorted array) the inner loop immediately breaks resulting in a total complexity of O(n)
.