Posts

Showing posts from November, 2024

Some obstacles to clear and concise code.

# Noncritical function design We call functions for many reasons. Two very common reasons are "object creation" and "object modification". ## Creation functions A creation function promises to produce some new object. If it cannot produce the new object, it should fail. Please note that this is not limited to constructors. It can be a function, for example, with a signature like this (C++): `auto read_file(std::filesystem::path const& filename) -> std::vector<std::byte>;` ## Modification functions A modification function promises to make a certain change to an existing object. If it cannot make the promised change, it should fail. The target object should either be in its original condition, or it should be considered to be in a valid-but-unknown state after the call, and the caller should probably just destroy it. Each modification function should pick one of these techniques for maintaining the target object after failure. In C++ land, these are calle...

Thoughts about sorting algorithms

I was thinking about `heapsort` earlier. It's really a pretty sweet algorithm (I even implemented it earlier (and did not test it)). * Like `quicksort`, (and unlike `mergesort`) it can be done in-place. * Like `mergesort`, (and unlike `quicksort`) it has `O(nlogn)` runtime complexity. If the range to be sorted doesn't fit in the cache, `heapsort` probably does worse than `mergesort`, because `mergesort` is mostly sequential access and `heapsort` does a lot of jumping around. `mergesort` can also be modified to benefit from partially-sorted data. I bet a modified `mergesort` that leverages already-sorted subranges and uses `heapsort` to benefit from cache-locality when creating subranges to be merged would perform quite well! I just googled hybrid sorts to see if this one already exists. `introsort` is a hybrid sort that uses `quicksort` at the top level and switches to `heapsort` to handle degenerate `quicksort` cases and switches to `insertion sort` sort small subranges. This ...