Binary Search I know, the word binary screams binary tree. But no, binary search doesn’t require a tree at all. It’s usually implemented in an array. In Go, we can simply use a slice to do this. Note that a binary search can only be performed on a sorted array. The generic signature [S ~[]E,… Continue reading Binary Search in Go
Tag: slice
Copying slices in Go
As we know, Go slices hover on top of fixed arrays; modifying elements in a slice also modifies the underlying array. In some scenarios, that’s unacceptable. Hence, we need slice copying! 1. Use slices.Clone slices.Clone is available from Go 1.21 onward. What’s cool about it is that it takes care of the pre-allocation of space… Continue reading Copying slices in Go
Stack & Queue in Go
1. Stack This is your good ol’ LIFO (last-in, first-out) structure. Just imagine a Pringles tube. A basic stack should have the following methods: In Go, you can use a slice as the underlying data structure. Notice how initiating the store slice in the NewStack[T any]() constructor is optional? This is because we have enough… Continue reading Stack & Queue in Go
Sorting a slice in Go easily
1. The slice Package If your Go package is anything newer than 1.21, and the items in the slice are of the cmp.Ordered type, you should definitely use the slice.Sort() function. It only works if you intend to sort it in place and in ascending order, though. So if we want to sort something in… Continue reading Sorting a slice in Go easily