A stable and adaptive quadratic sorting algorithm. [Best: O(n), Average: O(n2), Worst: O(n2), Space: O(1)]
Idea
The idea of insertion sort is to start with a sorted array of the first item on the left, and move one unsorted item to correct position by comparing with the sorted items, and repeat until all items are sorted.
There are two noteworthy advantages of insertion sort. First, insertion sort is stable in nature. The relative order of items with equal key remains unchanged before and after sorting. Second, insertion sort is very efficient on almost already sorted arrays.
First Implementation in Go
Below is my first implementation. It’s concise since I can perform the swaps without temporary variable, thanks to golang’s parallel assignment.
package sorting |
Optimization
The above implementation leaves rooms for performance tuning. In the outer loop, to move an item with k swaps takes 2k operations. It can be cut down to half by shifting each item to its neighbor with only k operations.
package sorting |
With the help of go benchmark tool, we see a constant performance growth of around 2x after optimization.
► go test -bench=. |
References: