Sorting in Go – Don’t Reinvent This Wheel
The post Sorting in Go – Don’t Reinvent This Wheel appeared first on Qvault . Sorting is a common task in programming, and for that reason most languages have a default sorting algorithm in their standard library. Go is one such language. Go has gone about providing sort functionality in one of the most elegant ways possible, via an interface. 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) } Any type that satisfies this interface can be sorted using the standard library’s sort.Sort() function. There is rarely a reason to sort any other way because the sort function is O(n log(n)) in the worst case. You can take a look at the various algorithms that are used, depending on the data to be sorted, here . Sorting a Slice The first thing...